System.Data.SQLite
Check-in [2b553f96c4]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:1.0.53.0
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | sourceforge
Files: files | file ages | folders
SHA1: 2b553f96c4bdf4f6edbd1c7f6557226737385da1
User & Date: rmsimpson 2008-07-24 06:19:59
Context
2008-07-26
04:34
1.0.54.0 check-in: 41d8f0f895 user: rmsimpson tags: sourceforge
2008-07-24
06:19
1.0.53.0 check-in: 2b553f96c4 user: rmsimpson tags: sourceforge
2008-07-16
23:32
1.0.52.0 check-in: 1084c98790 user: rmsimpson tags: sourceforge
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to Doc/Extra/dbfactorysupport.html.

93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<configuration>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite"/>
      <add name="SQLite Data Provider" invariant="System.Data.SQLite" 
           description=".Net Framework Data Provider for SQLite"
           type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite,
                 Version=1.0.52.0, Culture=neutral,
                 PublicKeyToken=db937bc2d44ff139"/>
    </DbProviderFactories>
  </system.data>
</configuration>
</pre>
      </div>
      <p>







|







93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
&lt;configuration&gt;
  &lt;system.data&gt;
    &lt;DbProviderFactories&gt;
      &lt;remove invariant="System.Data.SQLite"/&gt;
      &lt;add name="SQLite Data Provider" invariant="System.Data.SQLite" 
           description=".Net Framework Data Provider for SQLite"
           type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite,
                 Version=1.0.53.0, Culture=neutral,
                 PublicKeyToken=db937bc2d44ff139"/&gt;
    &lt;/DbProviderFactories&gt;
  &lt;/system.data&gt;
&lt;/configuration&gt;
</pre>
      </div>
      <p>

Changes to Doc/Extra/version.html.

51
52
53
54
55
56
57

















58
59
60
61
62
63
64
          </td>
        </tr>
      </table>
    </div>
    <div id="mainSection">
    <div id="mainBody">
    <h1 class="heading">Version History</h1>

















    <p><b>1.0.52.0 - July 16, 2008</b></p>
    <ul>
      <li>Code merge with SQLite 3.6.0</li>
      <li>Added a lot of previously-missing exports to the DEF file for the 
        native library.</li>
      <li>Fixed SQLiteDataReader to check for an invalid connection before operating on 
        an open cursor.</li>







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
          </td>
        </tr>
      </table>
    </div>
    <div id="mainSection">
    <div id="mainBody">
    <h1 class="heading">Version History</h1>
    <p><b>1.0.53.0 - July 24, 2008</b></p>
    <ul>
      <li>Enabled sqlite_load_extension</li>
      <li>Added retry/timeout code to SQLite3.Prepare() when preparing statements for 
        execution and a SQLITE_BUSY error occurs.</li>
      <li>Added a new schema to SQLiteConnection.GetSchema() called <i>Triggers</i>.&nbsp; 
        Used to retrieve the trigger(s) associated with a database and/or table/view.</li>
      <li>Extensive updates to table/view editing capabilities inside Visual Studio&#39;s 
        Server Explorer.&nbsp; The program now parses and lets you edit CHECK constraints and 
        triggers on a table, as well as define triggers on views.&nbsp; Experimental 
        still, so e-mail me if you have issues.</li>
      <li>Minor bugfix to the ViewColumns schema to return the proper base column name 
        for a view that aliases a column.</li>
      <li>Fixed the insert/update/delete DML support in the Linq module.</li>
      <li>Changed the behavior of SQLiteCommand to allow a transaction to be set even if 
        the command hasn&#39;t been associated with a connection yet.</li>
    </ul>
    <p><b>1.0.52.0 - July 16, 2008</b></p>
    <ul>
      <li>Code merge with SQLite 3.6.0</li>
      <li>Added a lot of previously-missing exports to the DEF file for the 
        native library.</li>
      <li>Fixed SQLiteDataReader to check for an invalid connection before operating on 
        an open cursor.</li>

Changes to Doc/Extra/welcome.html.

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
...
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
      </DIV>
      <h1 class="heading">What's New?</h1>
      <p><a href="version.html">Click here to see the version history of this SQLite.NET 
          provider</a></p>
      <DIV>
        <br>
      </DIV>
      <h1 class="heading">What's Coming Up?</h1>
      <p>There's a few things I'm aiming to do in the near future:&nbsp;</p>
      <DIV>
        <ul>
          <LI>
            Trigger design/view support from the Visual Studio Server Explorer and the 
            ability to create/edit views.</LI>
          </ul>
      </DIV>
      <br>
      <h1 class="heading">Using this library</h1>
      <p>The following are links to information on various aspects of the library and 
        how to use it in your application(s)
      </p>
      <p><a href="designer.html">How to install&nbsp;Visual Studio Design-Time Support</a></p>
      <P><A href="dbfactorysupport.html">How to configure and enumerate SQLite.NET 
          through the DbProviderFactories object</A></P>
................................................................................
        <LI>
        Written from scratch on VS2005/2008 specifically for ADO.NET 2.0, implenting all the
        base classes and features recently introduced in the framework, including automatic
        transaction enlistment.<li>Supports the Full and Compact .NET Framework, as well as
          native C/C++ development.&nbsp; 100% binary compatible with the original sqlite3.dll.
        </li>
        <li>
        On the Compact Framework, it is faster than the newly-introduced Sql Server Mobile.
          SQLite's installed size is a fraction of Sql Mobile's. It uses less memory at runtime,
          runs queries faster, and has a smaller database file size as well. </li>
        <li>Encrypted database support.&nbsp; Encrypted databases are fully encrypted and
          support both binary and cleartext password types. </li>
        <li>Visual Studio 2005/2008 Design-Time Support.&nbsp; You can add a SQLite 
        database to the Servers list, design queries with the Query Designer, 
        drag-and-drop tables onto a Typed DataSet, etc. </li>


        <li>
        Single file redistributable.&nbsp; The core sqlite3 codebase and the ADO.NET wrapper 
        are combined into one multi-module assembly. </li>
        <li>Binaries included for Itanium, x64, x86 and ARM processors. </li>
        <li>
        DbProviderFactory support. </li>
        <li>
................................................................................
          Full support for ATTACH'ed databases.&nbsp; Exposed as <i>Catalogs</i>
        in the schema.&nbsp; When cloning a connection, all attached databases are 
        automatically re-attached to the new connection. </li>
        <li>
          DbConnection.GetSchema(...) support includes the <i>MetaDataCollections</i>, <i>
          DataSourceInformation</i>, <i>Columns</i>, <i>Tables</i>, <i>Views, ViewColumns, </i>
          <i>Catalogs, </i><i>Indexes, 
            IndexColumns </i>and <em>ForeignKeys</em>
        keywords.
        </li>
        <li>
        Enhanced DbDataReader.GetSchemaTable() functionality returns catalog, namespace 
        and detailed schema information even for complex queries. </li>
        <li>
        Named and unnamed parameters. </li>
        <li>







<
<
<
<
<
<
<
<
<
<







 







|






|
>
>







 







|
<







69
70
71
72
73
74
75










76
77
78
79
80
81
82
..
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
      </DIV>
      <h1 class="heading">What's New?</h1>
      <p><a href="version.html">Click here to see the version history of this SQLite.NET 
          provider</a></p>
      <DIV>
        <br>
      </DIV>










      <h1 class="heading">Using this library</h1>
      <p>The following are links to information on various aspects of the library and 
        how to use it in your application(s)
      </p>
      <p><a href="designer.html">How to install&nbsp;Visual Studio Design-Time Support</a></p>
      <P><A href="dbfactorysupport.html">How to configure and enumerate SQLite.NET 
          through the DbProviderFactories object</A></P>
................................................................................
        <LI>
        Written from scratch on VS2005/2008 specifically for ADO.NET 2.0, implenting all the
        base classes and features recently introduced in the framework, including automatic
        transaction enlistment.<li>Supports the Full and Compact .NET Framework, as well as
          native C/C++ development.&nbsp; 100% binary compatible with the original sqlite3.dll.
        </li>
        <li>
        On the Compact Framework, it is faster than Sql Server Mobile.
          SQLite's installed size is a fraction of Sql Mobile's. It uses less memory at runtime,
          runs queries faster, and has a smaller database file size as well. </li>
        <li>Encrypted database support.&nbsp; Encrypted databases are fully encrypted and
          support both binary and cleartext password types. </li>
        <li>Visual Studio 2005/2008 Design-Time Support.&nbsp; You can add a SQLite 
        database to the Servers list, design queries with the Query Designer, 
        drag-and-drop tables onto a Typed DataSet, etc.</li>
            <li>Full SQLite schema editing inside Visual Studio.&nbsp; You can create/edit 
              tables, views, triggers, indexes, check constraints and foreign keys. </li>
        <li>
        Single file redistributable.&nbsp; The core sqlite3 codebase and the ADO.NET wrapper 
        are combined into one multi-module assembly. </li>
        <li>Binaries included for Itanium, x64, x86 and ARM processors. </li>
        <li>
        DbProviderFactory support. </li>
        <li>
................................................................................
          Full support for ATTACH'ed databases.&nbsp; Exposed as <i>Catalogs</i>
        in the schema.&nbsp; When cloning a connection, all attached databases are 
        automatically re-attached to the new connection. </li>
        <li>
          DbConnection.GetSchema(...) support includes the <i>MetaDataCollections</i>, <i>
          DataSourceInformation</i>, <i>Columns</i>, <i>Tables</i>, <i>Views, ViewColumns, </i>
          <i>Catalogs, </i><i>Indexes, 
            IndexColumns, ForeignKeys </i>and <em>Triggers</em>.

        </li>
        <li>
        Enhanced DbDataReader.GetSchemaTable() functionality returns catalog, namespace 
        and detailed schema information even for complex queries. </li>
        <li>
        Named and unnamed parameters. </li>
        <li>

Changes to Doc/SQLite.NET.chm.

cannot compute difference between binary files

Changes to SQLite.Designer/ChangePasswordDialog.cs.








1
2
3
4
5
6
7







namespace SQLite.Designer
{
  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer
{
  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;

Added SQLite.Designer/ChangeScriptDialog.Designer.cs.



























































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
namespace SQLite.Designer
{
  partial class ChangeScriptDialog
  {
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
      if (disposing && (components != null))
      {
        components.Dispose();
      }
      base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      System.Windows.Forms.PictureBox pictureBox1;
      System.Windows.Forms.Label label1;
      System.Windows.Forms.Button noButton;
      System.Windows.Forms.Button yesButton;
      this._script = new System.Windows.Forms.RichTextBox();
      pictureBox1 = new System.Windows.Forms.PictureBox();
      label1 = new System.Windows.Forms.Label();
      noButton = new System.Windows.Forms.Button();
      yesButton = new System.Windows.Forms.Button();
      ((System.ComponentModel.ISupportInitialize)(pictureBox1)).BeginInit();
      this.SuspendLayout();
      // 
      // pictureBox1
      // 
      pictureBox1.Image = global::SQLite.Designer.VSPackage.info;
      pictureBox1.Location = new System.Drawing.Point(13, 13);
      pictureBox1.Name = "pictureBox1";
      pictureBox1.Size = new System.Drawing.Size(48, 48);
      pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
      pictureBox1.TabIndex = 0;
      pictureBox1.TabStop = false;
      // 
      // label1
      // 
      label1.AutoSize = true;
      label1.Location = new System.Drawing.Point(67, 31);
      label1.Name = "label1";
      label1.Size = new System.Drawing.Size(200, 13);
      label1.TabIndex = 1;
      label1.Text = "Do you want to save this script to a file?";
      // 
      // noButton
      // 
      noButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
      noButton.Location = new System.Drawing.Point(445, 362);
      noButton.Name = "noButton";
      noButton.Size = new System.Drawing.Size(75, 25);
      noButton.TabIndex = 3;
      noButton.Text = "&No";
      noButton.UseVisualStyleBackColor = true;
      noButton.Click += new System.EventHandler(this.noButton_Click);
      // 
      // yesButton
      // 
      yesButton.Location = new System.Drawing.Point(364, 362);
      yesButton.Name = "yesButton";
      yesButton.Size = new System.Drawing.Size(75, 25);
      yesButton.TabIndex = 4;
      yesButton.Text = "&Yes";
      yesButton.UseVisualStyleBackColor = true;
      yesButton.Click += new System.EventHandler(this.yesButton_Click);
      // 
      // _script
      // 
      this._script.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
      this._script.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
      this._script.Location = new System.Drawing.Point(12, 76);
      this._script.Name = "_script";
      this._script.ReadOnly = true;
      this._script.Size = new System.Drawing.Size(508, 280);
      this._script.TabIndex = 2;
      this._script.Text = "";
      this._script.WordWrap = false;
      // 
      // ChangeScriptDialog
      // 
      this.AcceptButton = yesButton;
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
      this.CancelButton = noButton;
      this.ClientSize = new System.Drawing.Size(532, 399);
      this.Controls.Add(yesButton);
      this.Controls.Add(noButton);
      this.Controls.Add(this._script);
      this.Controls.Add(label1);
      this.Controls.Add(pictureBox1);
      this.Font = new System.Drawing.Font("MS Shell Dlg 2", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
      this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
      this.MaximizeBox = false;
      this.MinimizeBox = false;
      this.Name = "ChangeScriptDialog";
      this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
      this.Text = "Save Change Script";
      ((System.ComponentModel.ISupportInitialize)(pictureBox1)).EndInit();
      this.ResumeLayout(false);
      this.PerformLayout();

    }

    #endregion

    private System.Windows.Forms.RichTextBox _script;

  }
}

Added SQLite.Designer/ChangeScriptDialog.cs.



















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer
{
  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Text;
  using System.Windows.Forms;
  using SQLite.Designer.Design;

  public partial class ChangeScriptDialog : Form
  {
    private string _tableName;

    public ChangeScriptDialog(string tableName, string script)
    {
      _tableName = tableName;
      InitializeComponent();

      _script.Text = script;
    }

    private void noButton_Click(object sender, EventArgs e)
    {
      DialogResult = DialogResult.Cancel;
      Close();
    }

    private void yesButton_Click(object sender, EventArgs e)
    {
      using (SaveFileDialog save = new SaveFileDialog())
      {
        save.DefaultExt = "sql";
        save.OverwritePrompt = true;
        save.Filter = "SQL Script Files (*.sql)|*.sql|All Files (*.*)|*.*";
        save.FileName = String.Format("{0}.sql", _tableName);
        save.Title = "Save SQLite Change Script";

        DialogResult = save.ShowDialog(this);

        if (DialogResult == DialogResult.OK)
        {
          System.IO.File.WriteAllText(save.FileName, _script.Text.Replace("\r", "").Replace("\n", "\r\n"), Encoding.UTF8);
        }
      }
      Close();
    }
  }
}

Added SQLite.Designer/ChangeScriptDialog.resx.









































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
<?xml version="1.0" encoding="utf-8"?>
<root>
  <!-- 
    Microsoft ResX Schema 
    
    Version 2.0
    
    The primary goals of this format is to allow a simple XML format 
    that is mostly human readable. The generation and parsing of the 
    various data types are done through the TypeConverter classes 
    associated with the data types.
    
    Example:
    
    ... ado.net/XML headers & schema ...
    <resheader name="resmimetype">text/microsoft-resx</resheader>
    <resheader name="version">2.0</resheader>
    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
        <value>[base64 mime encoded serialized .NET Framework object]</value>
    </data>
    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
        <comment>This is a comment</comment>
    </data>
                
    There are any number of "resheader" rows that contain simple 
    name/value pairs.
    
    Each data row contains a name, and value. The row also contains a 
    type or mimetype. Type corresponds to a .NET class that support 
    text/value conversion through the TypeConverter architecture. 
    Classes that don't support this are serialized and stored with the 
    mimetype set.
    
    The mimetype is used for serialized objects, and tells the 
    ResXResourceReader how to depersist the object. This is currently not 
    extensible. For a given mimetype the value must be set accordingly:
    
    Note - application/x-microsoft.net.object.binary.base64 is the format 
    that the ResXResourceWriter will generate, however the reader can 
    read any of the formats listed below.
    
    mimetype: application/x-microsoft.net.object.binary.base64
    value   : The object must be serialized with 
            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            : and then encoded with base64 encoding.
    
    mimetype: application/x-microsoft.net.object.soap.base64
    value   : The object must be serialized with 
            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
            : and then encoded with base64 encoding.

    mimetype: application/x-microsoft.net.object.bytearray.base64
    value   : The object must be serialized into a byte array 
            : using a System.ComponentModel.TypeConverter
            : and then encoded with base64 encoding.
    -->
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" use="required" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <metadata name="pictureBox1.GenerateMember" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <value>False</value>
  </metadata>
  <metadata name="label1.GenerateMember" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <value>False</value>
  </metadata>
  <metadata name="noButton.GenerateMember" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <value>False</value>
  </metadata>
  <metadata name="yesButton.GenerateMember" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <value>False</value>
  </metadata>
</root>

Added SQLite.Designer/Design/Check.cs.











































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer.Design
{
  using System;
  using System.Collections.Generic;
  using System.Collections;
  using System.Text;
  using System.ComponentModel;
  using System.Data;
  using System.Data.Common;
  using System.ComponentModel.Design;
  using System.Drawing.Design;
  using System.Windows.Forms;

  internal class CheckEditor : CollectionEditor
  {
    Table _table;
    CollectionEditor.CollectionForm _form;
    object[] _items;
    object[] _orig;
    int _count;

    internal CheckEditor(Table parent)
      : base(typeof(List<string>))
    {
      _table = parent;
    }

    protected override CollectionEditor.CollectionForm CreateCollectionForm()
    {
      _form = base.CreateCollectionForm();
      _form.Text = "CHECK Constraint Editor";
      _form.Width = (int)(_form.Width * 1.25);
      _form.Height = (int)(_form.Height * 1.25);
      return _form;
    }

    protected override object CreateInstance(Type itemType)
    {
      if (itemType == typeof(string)) return String.Empty;
      return base.CreateInstance(itemType);
    }

    protected override object[] GetItems(object editValue)
    {
      if (_items == null)
      {
        List<string> items = editValue as List<string>;
        _items = new object[items.Count];
        _orig = new object[items.Count];

        for (int n = 0; n < _items.Length; n++)
        {
          _items[n] = items[n];
          _orig[n] = items[n];
        }
        _count = _items.Length;
      }
      return _items;
    }

    protected override object SetItems(object editValue, object[] value)
    {
      bool dirty = false;
      if (editValue != null)
      {
        int length = this.GetItems(editValue).Length;
        int num2 = value.Length;
        if (!(editValue is IList))
        {
          return editValue;
        }
        IList list = (IList)editValue;
        list.Clear();
        for (int i = 0; i < value.Length; i++)
        {
          string val = value[i] as string;

          if (String.IsNullOrEmpty(val) == false)
          {
            list.Add(val);
            if (i < _orig.Length && val != (string)_orig[i])
              dirty = true;
          }
        }
        if (list.Count != _count)
          dirty = true;

        if (dirty == true && _form.DialogResult == DialogResult.OK)
          _table._owner.MakeDirty();
      }
      return editValue;
    }
  }
}

Changes to SQLite.Designer/Design/Column.cs.










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
..
79
80
81
82
83
84
85





86
87
88
89
90
91
92
..
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
...
243
244
245
246
247
248
249



250
251
252
253
254
255
256
257
258
259
260
261
262
263









using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Drawing.Design;
using System.Data;
using System.Data.Common;

namespace SQLite.Designer.Design
{
  internal class Column : IHaveConnection
  {
    private bool _allowNulls = false;
    private string _dataType = "";
    private string _defaultValue = "";
    private string _columnName = "";
    private string _origName = "";
    private string _collate;
    private DataGridViewRow _parent;
    private string _checkconstraint = "";
    private Unique _unique;
    //private PrimaryKey _primaryKey;
    private Table _table;

    internal Column(Table table, DataGridViewRow row)
    {
      _parent = row;
      _table = table as Table;
      _unique = new Unique(this);
      //_primaryKey = new PrimaryKey(this);
    }

    internal Column(DataRow row, Table source)
    {
      _table = source;
      _unique = new Unique(this, row);
      //_primaryKey = new PrimaryKey(this, row);

      if (row.IsNull("AUTOINCREMENT") == false && (bool)row["AUTOINCREMENT"] == true)
        _table.PrimaryKey.AutoIncrement = true;

      _dataType = (row.IsNull("DATA_TYPE") == false) ? row["DATA_TYPE"].ToString() : String.Empty;
      _columnName = row["COLUMN_NAME"].ToString();
      _origName = _columnName;
................................................................................


    [Browsable(false)]
    internal Table Table
    {
      get { return _table; }
    }






    internal DataGridViewRow Parent
    {
      get { return _parent; }
      set 
      {
        _parent = value;
................................................................................

    internal void RefreshGrid()
    {
      if (_parent == null) return;
      _parent.DataGridView.Refresh();
    }

    internal void CellValueChanged()
    {
      if (_parent == null) return;
      if (_parent.DataGridView.CurrentCell.RowIndex != _parent.Index) return;

      object value;

      if (_parent.DataGridView.CurrentCell.IsInEditMode == true)
      {
        if (_parent.DataGridView.EditingControl != null)
          value = ((IDataGridViewEditingControl)_parent.DataGridView.EditingControl).EditingControlFormattedValue;
        else
          value = _parent.DataGridView.CurrentCell.EditedFormattedValue;
      }
      else
        value = _parent.DataGridView.CurrentCell.Value;

      switch (_parent.DataGridView.CurrentCell.ColumnIndex)


      {
        case 0:
          ColumnName = value.ToString();
          break;
        case 1:
          DataType = value.ToString();
          break;
        case 2:
          AllowNulls = Convert.ToBoolean(value);
          break;
      }
    }

    [DisplayName("Check")]
    [Category("Constraints")]
    public virtual string CheckConstraint
    {
      get { return _checkconstraint; }
      set
      {
        if (_checkconstraint != value)
        {
          _checkconstraint = value;
          _table._owner.MakeDirty();
        }
      }
    }

    [DefaultValue("BINARY")]
    [Category("Constraints")]


    public virtual string Collate
    {
      get { return _collate; }
      set
      {
        if (String.IsNullOrEmpty(value)) value = "BINARY";
        if (_collate != value)
        {
          _collate = value;




          _table._owner.MakeDirty();
        }
      }
    }

    [Category("Constraints")]

    public virtual Unique Unique
    {
      get { return _unique; }
    }

    [Browsable(false)]
    public virtual string ColumnName
    {
      get { return _columnName; }




      set { _columnName = value; }



    }

    [Browsable(false)]
    public virtual string OriginalName
    {
      get { return _origName; }
    }

    //[DisplayName("Primary Key")]
    //[Category("Constraints")]
    //public virtual PrimaryKey PrimaryKey
    //{
    //  get { return _primaryKey; }
    //}

    [DefaultValue(false)]
    [DisplayName("Allow Nulls")]
    [Category("Constraints")]

    public virtual bool AllowNulls
    {
      get { return _allowNulls; }
      set
      {
        if (value != _allowNulls)
        {
          _allowNulls = value;
          if (_parent == null) return;
          _parent.Cells[2].Value = _allowNulls;

        }
      }
    }

    [Browsable(false)]
    public virtual string DataType
    {
      get { return _dataType; }




      set { _dataType = value; }



    }

    [DisplayName("Default Value")]
    [Category("Constraints")]

    public virtual string DefaultValue
    {
      get { return _defaultValue; }
      set { _defaultValue = value; }
    }

    internal void WriteSql(StringBuilder builder)
................................................................................
        if (_table.PrimaryKey.AutoIncrement == true)
          builder.Append(" AUTOINCREMENT");
      }

      if (AllowNulls == false)
        builder.Append(" NOT NULL");




      if (Unique.Enabled == true && isprimary == false)
      {
        builder.Append(" UNIQUE");
        if (Unique.Conflict != ConflictEnum.Abort)
          builder.AppendFormat(" ON CONFLICT {0}", Unique.Conflict.ToString());
      }

      if (String.IsNullOrEmpty(CheckConstraint) == false)
      {
        builder.AppendFormat(" CONSTRAINT CK_{0}_{1} CHECK ({2})", _table.Name, ColumnName, CheckConstraint);
      }
    }
  }
}
>
>
>
>
>
>
>
>
>
|
|
|
|
|
|
|
|
|

<
<









<

<







<






<







 







>
>
>
>
>







 







|


|



|




|


|

|
>
>













<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


>
>









>
>
>
>






>









>
>
>
>
|
>
>
>








<
<
<
<
<
<
<



>










>








>
>
>
>
|
>
>
>




>







 







>
>
>




|
<
<
<
<
<




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
..
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
...
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
...
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269





270
271
272
273
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer.Design
{
  using System;
  using System.Collections.Generic;
  using System.Text;
  using System.ComponentModel;
  using System.ComponentModel.Design;
  using System.Windows.Forms;
  using System.Drawing.Design;
  using System.Data;
  using System.Data.Common;



  internal class Column : IHaveConnection
  {
    private bool _allowNulls = false;
    private string _dataType = "";
    private string _defaultValue = "";
    private string _columnName = "";
    private string _origName = "";
    private string _collate;
    private DataGridViewRow _parent;

    private Unique _unique;

    private Table _table;

    internal Column(Table table, DataGridViewRow row)
    {
      _parent = row;
      _table = table as Table;
      _unique = new Unique(this);

    }

    internal Column(DataRow row, Table source)
    {
      _table = source;
      _unique = new Unique(this, row);


      if (row.IsNull("AUTOINCREMENT") == false && (bool)row["AUTOINCREMENT"] == true)
        _table.PrimaryKey.AutoIncrement = true;

      _dataType = (row.IsNull("DATA_TYPE") == false) ? row["DATA_TYPE"].ToString() : String.Empty;
      _columnName = row["COLUMN_NAME"].ToString();
      _origName = _columnName;
................................................................................


    [Browsable(false)]
    internal Table Table
    {
      get { return _table; }
    }

    internal void Committed()
    {
      _origName = ColumnName;
    }

    internal DataGridViewRow Parent
    {
      get { return _parent; }
      set 
      {
        _parent = value;
................................................................................

    internal void RefreshGrid()
    {
      if (_parent == null) return;
      _parent.DataGridView.Refresh();
    }

    internal void CellValueChanged(int rowIndex, int cellIndex)
    {
      if (_parent == null) return;
      if (rowIndex != _parent.Index) return;

      object value;

      if (_parent.Cells[cellIndex].IsInEditMode == true)
      {
        if (_parent.DataGridView.EditingControl != null)
          value = ((IDataGridViewEditingControl)_parent.DataGridView.EditingControl).EditingControlFormattedValue;
        else
          value = _parent.Cells[cellIndex].EditedFormattedValue;
      }
      else
        value = _parent.Cells[cellIndex].Value;

      if (value == null) value = String.Empty;

      switch (cellIndex)
      {
        case 0:
          ColumnName = value.ToString();
          break;
        case 1:
          DataType = value.ToString();
          break;
        case 2:
          AllowNulls = Convert.ToBoolean(value);
          break;
      }
    }
















    [DefaultValue("BINARY")]
    [Category("Constraints")]
    [Editor(typeof(CollationTypeEditor), typeof(UITypeEditor))]
    [Description("The collation sequence to use for the column.  This will affect comparison and equality tests against the column.")]
    public virtual string Collate
    {
      get { return _collate; }
      set
      {
        if (String.IsNullOrEmpty(value)) value = "BINARY";
        if (_collate != value)
        {
          _collate = value;
          
          if (_table.PrimaryKey.Columns.Count == 1 && String.Compare(ColumnName, _table.PrimaryKey.Columns[0].Column, StringComparison.OrdinalIgnoreCase) == 0)
            _table.PrimaryKey.Columns[0].Collate = value;

          _table._owner.MakeDirty();
        }
      }
    }

    [Category("Constraints")]
    [Description("The unique constraints of the column")]
    public virtual Unique Unique
    {
      get { return _unique; }
    }

    [Browsable(false)]
    public virtual string ColumnName
    {
      get { return _columnName; }
      set
      {
        if (value != _columnName)
        {
          _columnName = value;
          _table.MakeDirty();
        }
      }
    }

    [Browsable(false)]
    public virtual string OriginalName
    {
      get { return _origName; }
    }








    [DefaultValue(false)]
    [DisplayName("Allow Nulls")]
    [Category("Constraints")]
    [Description("Specifies whether or not the column will allow NULL values.")]
    public virtual bool AllowNulls
    {
      get { return _allowNulls; }
      set
      {
        if (value != _allowNulls)
        {
          _allowNulls = value;
          if (_parent == null) return;
          _parent.Cells[2].Value = _allowNulls;
          _table.MakeDirty();
        }
      }
    }

    [Browsable(false)]
    public virtual string DataType
    {
      get { return _dataType; }
      set
      {
        if (value != _dataType)
        {
          _dataType = value;
          _table.MakeDirty();
        }
      }
    }

    [DisplayName("Default Value")]
    [Category("Constraints")]
    [Description("The default value to populate in the column when an explicit value is not specified.")]
    public virtual string DefaultValue
    {
      get { return _defaultValue; }
      set { _defaultValue = value; }
    }

    internal void WriteSql(StringBuilder builder)
................................................................................
        if (_table.PrimaryKey.AutoIncrement == true)
          builder.Append(" AUTOINCREMENT");
      }

      if (AllowNulls == false)
        builder.Append(" NOT NULL");

      if (String.IsNullOrEmpty(Collate) == false && String.Compare(Collate, "BINARY", StringComparison.OrdinalIgnoreCase) != 0)
        builder.AppendFormat(" COLLATE {0}", Collate.ToUpperInvariant());

      if (Unique.Enabled == true && isprimary == false)
      {
        builder.Append(" UNIQUE");
        if (Unique.Conflict != ConflictEnum.Abort)
          builder.AppendFormat(" ON CONFLICT {0}", Unique.Conflict.ToString().ToUpperInvariant());





      }
    }
  }
}

Changes to SQLite.Designer/Design/ForeignKey.cs.










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
..
32
33
34
35
36
37
38
39
40

41
42




43
44
45
46
47
48



49
50
51
52
53
54
55
..
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
...
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
...
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
...
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









using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Windows.Forms;

namespace SQLite.Designer.Design
{
  internal class ForeignKeyEditor : CollectionEditor
  {
    Table _table;
    bool _cancel = false;
    object[] _items;



    internal ForeignKeyEditor(Table parent)
      : base(typeof(List<ForeignKey>))
    {
      _table = parent;




















    }

    protected override object CreateInstance(Type itemType)
    {
      if (itemType == typeof(ForeignKey))
      {
        return new ForeignKey(null, _table, null);
................................................................................
      throw new NotSupportedException();
    }

    protected override object[] GetItems(object editValue)
    {
      if (_items == null)
      {
        List<ForeignKey> value = editValue as List<ForeignKey>;
        _items = new object[value.Count];

        for (int n = 0; n < _items.Length; n++)
          _items[n] = value[n].Clone();




      }
      return _items;
    }

    protected override object SetItems(object editValue, object[] value)
    {



      if (editValue != null)
      {
        int length = this.GetItems(editValue).Length;
        int num2 = value.Length;
        if (!(editValue is IList))
        {
          return editValue;
................................................................................
        list.Clear();
        for (int i = 0; i < value.Length; i++)
        {
          ForeignKey fkey = value[i] as ForeignKey;

          if (fkey != null && String.IsNullOrEmpty(fkey.From.Column) == false && String.IsNullOrEmpty(fkey.To.Catalog) == false &&
            String.IsNullOrEmpty(fkey.To.Table) == false && String.IsNullOrEmpty(fkey.To.Column) == false)



            list.Add(value[i]);
        }
      }
      
      if (_cancel == false)

        _table._owner.MakeDirty();

      return editValue;
    }

    protected override void CancelChanges()
    {
      _cancel = true;
    }
  }

  internal class ForeignKeyItem : IHaveConnectionScope
  {
    private string _catalog;
    private string _table;
    private string _column;
................................................................................
    public virtual string Column
    {
      get { return _column; }
    }

    protected void SetCatalog(string value)
    {


      _catalog = value;


    }

    protected void SetTable(string value)
    {


      _table = value;


    }

    protected void SetColumn(string value)
    {


      _column = value;


    }
  }

  [TypeConverter(typeof(ExpandableObjectConverter))]
  internal class ForeignKeyFromItem : ForeignKeyItem
  {
    internal ForeignKeyFromItem(ForeignKey fkey, string column)
      : base(fkey, fkey._table.Catalog, fkey._table.Name, column)
    {
    }

    [Editor(typeof(ColumnsTypeEditor), typeof(UITypeEditor))]

    public new string Column
    {
      get { return base.Column; }
      set { SetColumn(value); }
    }

    [Browsable(false)]
................................................................................
    internal ForeignKeyToItem(ForeignKey fkey, string catalog, string table, string column)
      : base(fkey, catalog, table, column)
    {
    }

    [Browsable(false)]
    [Editor(typeof(CatalogTypeEditor), typeof(UITypeEditor))]

    public new string Catalog
    {
      get
      {
        return base.Catalog;
      }
      set
................................................................................
      {
        SetCatalog(value);
      }
    }

    [DisplayName("Base Table")]
    [Editor(typeof(TablesTypeEditor), typeof(UITypeEditor))]

    public new string Table
    {
      get { return base.Table; }
      set { SetTable(value); }
    }

    [Editor(typeof(ColumnsTypeEditor), typeof(UITypeEditor))]

    public new string Column
    {
      get { return base.Column; }
      set { SetColumn(value); }
    }
  }

................................................................................
  [DefaultProperty("From")]
  internal class ForeignKey : IHaveConnection, ICloneable
  {
    internal Table _table;
    internal ForeignKeyFromItem _from;
    internal ForeignKeyToItem _to;
    internal string _name;


    private ForeignKey(ForeignKey source)
    {
      _table = source._table;
      _from = new ForeignKeyFromItem(this, source._from.Column);
      _to = new ForeignKeyToItem(this, source._to.Catalog, source._to.Table, source._to.Column);
      _name = source._name;

















    }

    internal ForeignKey(DbConnection cnn, Table table, DataRow row)
    {
      _table = table;
      if (row != null)
      {
................................................................................
      {
        builder.AppendFormat("CONSTRAINT [{0}] FOREIGN KEY ([{1}]) REFERENCES [{3}] ([{4}])", Name, _from.Column, _to.Catalog, _to.Table, _to.Column);
      }
    }

    [ParenthesizePropertyName(true)]
    [Category("Identity")]

    public string Name
    {
      get
      {
        if (String.IsNullOrEmpty(_name) == false) return _name;

        return String.Format("FK_{0}_{1}_{2}_{3}", _from.Table, _from.Column, _to.Table, _to.Column);
      }




      set { _name = value; }



    }

    #region IHaveConnection Members

    public DbConnection GetConnection()
    {
      return ((IHaveConnection)_table).GetConnection();
    }

    #endregion

    [DisplayName("Primary/Unique Key")]
    [Category("Source")]

    public ForeignKeyFromItem From
    {
      get { return _from; }
    }

    [DisplayName("Foreign Key")]
    [Category("Target")]

    public ForeignKeyToItem To
    {
      get { return _to; }
    }

    #region ICloneable Members

>
>
>
>
>
>
>
>
>
|
|
|
|
|
|
|
|
|
|

<
<



|

>
>





>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|
|
>

<
>
>
>
>






>
>
>







 







>
>
>

|
|
<
<
>
|
|


<
<
<
<
<







 







>
>
|
>
>




>
>
|
>
>




>
>
|
>
>












>







 







>







 







>







>







 







>







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>








>
>
>
>
|
>
>
>













>







>







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
..
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
..
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
...
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
...
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
...
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
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer.Design
{
  using System;
  using System.Collections.Generic;
  using System.Collections;
  using System.Text;
  using System.ComponentModel;
  using System.Data;
  using System.Data.Common;
  using System.ComponentModel.Design;
  using System.Drawing.Design;
  using System.Windows.Forms;



  internal class ForeignKeyEditor : CollectionEditor
  {
    Table _table;
    CollectionEditor.CollectionForm _form;
    object[] _items;
    object[] _orig;
    int _count;

    internal ForeignKeyEditor(Table parent)
      : base(typeof(List<ForeignKey>))
    {
      _table = parent;
      _count = _table.ForeignKeys.Count;
    }

    protected override CollectionEditor.CollectionForm CreateCollectionForm()
    {
      _form = base.CreateCollectionForm();
      _form.Text = "Foreign Key Editor";
      foreach (Control c in _form.Controls[0].Controls)
      {
        PropertyGrid grid = c as PropertyGrid;
        if (grid != null)
        {
          grid.HelpVisible = true;
          break;
        }
      }
      _form.Width = (int)(_form.Width * 1.25);
      _form.Height = (int)(_form.Height * 1.25);

      return _form;
    }

    protected override object CreateInstance(Type itemType)
    {
      if (itemType == typeof(ForeignKey))
      {
        return new ForeignKey(null, _table, null);
................................................................................
      throw new NotSupportedException();
    }

    protected override object[] GetItems(object editValue)
    {
      if (_items == null)
      {
        List<ForeignKey> items = editValue as List<ForeignKey>;
        _items = new object[items.Count];
        _orig = new object[items.Count];
        for (int n = 0; n < _items.Length; n++)

        {
          _items[n] = ((ICloneable)items[n]).Clone();
          _orig[n] = items[n];
        }
      }
      return _items;
    }

    protected override object SetItems(object editValue, object[] value)
    {
      bool dirty = false;
      if (_form.DialogResult == DialogResult.Cancel) value = _orig;

      if (editValue != null)
      {
        int length = this.GetItems(editValue).Length;
        int num2 = value.Length;
        if (!(editValue is IList))
        {
          return editValue;
................................................................................
        list.Clear();
        for (int i = 0; i < value.Length; i++)
        {
          ForeignKey fkey = value[i] as ForeignKey;

          if (fkey != null && String.IsNullOrEmpty(fkey.From.Column) == false && String.IsNullOrEmpty(fkey.To.Catalog) == false &&
            String.IsNullOrEmpty(fkey.To.Table) == false && String.IsNullOrEmpty(fkey.To.Column) == false)
          {
            if (fkey.IsDirty) dirty = true;

            list.Add(value[i]);
          }
        }


        if ((dirty == true || list.Count != _count) && _form.DialogResult == DialogResult.OK)
        _table.MakeDirty();      
      }
      return editValue;
    }





  }

  internal class ForeignKeyItem : IHaveConnectionScope
  {
    private string _catalog;
    private string _table;
    private string _column;
................................................................................
    public virtual string Column
    {
      get { return _column; }
    }

    protected void SetCatalog(string value)
    {
      if (_catalog != value)
      {
        _catalog = value;
        _fkey.MakeDirty();
      }
    }

    protected void SetTable(string value)
    {
      if (_table != value)
      {
        _table = value;
        _fkey.MakeDirty();
      }
    }

    protected void SetColumn(string value)
    {
      if (_column != value)
      {
        _column = value;
        _fkey.MakeDirty();
      }
    }
  }

  [TypeConverter(typeof(ExpandableObjectConverter))]
  internal class ForeignKeyFromItem : ForeignKeyItem
  {
    internal ForeignKeyFromItem(ForeignKey fkey, string column)
      : base(fkey, fkey._table.Catalog, fkey._table.Name, column)
    {
    }

    [Editor(typeof(ColumnsTypeEditor), typeof(UITypeEditor))]
    [Description("The primary (parent) column of the foreign key relationship")]
    public new string Column
    {
      get { return base.Column; }
      set { SetColumn(value); }
    }

    [Browsable(false)]
................................................................................
    internal ForeignKeyToItem(ForeignKey fkey, string catalog, string table, string column)
      : base(fkey, catalog, table, column)
    {
    }

    [Browsable(false)]
    [Editor(typeof(CatalogTypeEditor), typeof(UITypeEditor))]
    [Description("The database catalog (main, temp, or the name of an attached database) to which the foreign key refers.")]
    public new string Catalog
    {
      get
      {
        return base.Catalog;
      }
      set
................................................................................
      {
        SetCatalog(value);
      }
    }

    [DisplayName("Base Table")]
    [Editor(typeof(TablesTypeEditor), typeof(UITypeEditor))]
    [Description("The child table to which the foreign key refers.")]
    public new string Table
    {
      get { return base.Table; }
      set { SetTable(value); }
    }

    [Editor(typeof(ColumnsTypeEditor), typeof(UITypeEditor))]
    [Description("The child column to which the foreign key refers.")]
    public new string Column
    {
      get { return base.Column; }
      set { SetColumn(value); }
    }
  }

................................................................................
  [DefaultProperty("From")]
  internal class ForeignKey : IHaveConnection, ICloneable
  {
    internal Table _table;
    internal ForeignKeyFromItem _from;
    internal ForeignKeyToItem _to;
    internal string _name;
    private bool _dirty = false;

    private ForeignKey(ForeignKey source)
    {
      _table = source._table;
      _from = new ForeignKeyFromItem(this, source._from.Column);
      _to = new ForeignKeyToItem(this, source._to.Catalog, source._to.Table, source._to.Column);
      _name = source._name;
      _dirty = source._dirty;
    }

    internal void MakeDirty()
    {
      _dirty = true;
    }

    [Browsable(false)]
    internal bool IsDirty
    {
      get { return _dirty; }
    }

    internal void ClearDirty()
    {
      _dirty = false;
    }

    internal ForeignKey(DbConnection cnn, Table table, DataRow row)
    {
      _table = table;
      if (row != null)
      {
................................................................................
      {
        builder.AppendFormat("CONSTRAINT [{0}] FOREIGN KEY ([{1}]) REFERENCES [{3}] ([{4}])", Name, _from.Column, _to.Catalog, _to.Table, _to.Column);
      }
    }

    [ParenthesizePropertyName(true)]
    [Category("Identity")]
    [Description("The name of the foreign key.")]
    public string Name
    {
      get
      {
        if (String.IsNullOrEmpty(_name) == false) return _name;

        return String.Format("FK_{0}_{1}_{2}_{3}", _from.Table, _from.Column, _to.Table, _to.Column);
      }
      set
      {
        if (_name != value)
        {
          _name = value;
          MakeDirty();
        }
      }
    }

    #region IHaveConnection Members

    public DbConnection GetConnection()
    {
      return ((IHaveConnection)_table).GetConnection();
    }

    #endregion

    [DisplayName("Primary/Unique Key")]
    [Category("Source")]
    [Description("The source (parent) column in the current table that is to be the unique value of the foreign key.")]
    public ForeignKeyFromItem From
    {
      get { return _from; }
    }

    [DisplayName("Foreign Key")]
    [Category("Target")]
    [Description("The child table and column to which the specified parent column is related.")]
    public ForeignKeyToItem To
    {
      get { return _to; }
    }

    #region ICloneable Members

Changes to SQLite.Designer/Design/Index.cs.










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
..
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
...
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
...
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
...
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
...
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
...
320
321
322
323
324
325
326

327
328
329
330
331
332
333
334
335








336
337
338
339
340
341
342
...
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
...
380
381
382
383
384
385
386

387
388
389


390
391
392
393
394
395
396
397
...
401
402
403
404
405
406
407
408
















409

410
411
412




413



414
415
416
417
418
419
420
...
423
424
425
426
427
428
429


430
431
432
433
434
435
436
...
460
461
462
463
464
465
466




467



468
469
470
471
472



473
474
475
476
477
478
479
...
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









using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Windows.Forms;

namespace SQLite.Designer.Design
{
  internal class IndexEditor : CollectionEditor
  {
    Table _table;
    bool _cancel = false;
    object[] _items;



    internal IndexEditor(Table parent)
      : base(typeof(List<Index>))
    {
      _table = parent;
    }

    protected override object CreateInstance(Type itemType)
    {
      if (itemType == typeof(Index))
      {
        return new Index(null, _table, null);
      }
      throw new NotSupportedException();
    }

    protected override void CancelChanges()
    {
      _cancel = true;
    }

    protected override bool CanRemoveInstance(object value)
    {
      return !(value is PrimaryKey);
    }

    protected override object[] GetItems(object editValue)
    {
      if (_items == null)
      {
        List<Index> value = editValue as List<Index>;

        int extra = (_table.PrimaryKey.Columns.Count > 0) ? 1 : 0;

        _items = new object[value.Count + extra];

        for (int n = extra; n < _items.Length; n++)

          _items[n] = ((ICloneable)value[n - extra]).Clone();



        if (extra > 0)


          _items[0] = _table.PrimaryKey;
      }



      return _items;
    }














































    protected override object SetItems(object editValue, object[] value)
    {






      if (editValue != null)
      {
        int length = this.GetItems(editValue).Length;
        int num2 = value.Length;
        if (!(editValue is IList))
        {
          return editValue;
................................................................................
        for (int i = 0; i < value.Length; i++)
        {
          Index idx = value[i] as Index;

          if (idx is PrimaryKey)
          {
            _table.PrimaryKey = (PrimaryKey)idx;


          }
          else
          {
            if (idx != null && idx.Columns.Count > 0)


              list.Add(value[i]);



          }
        }
      }

      if (_cancel == false)
        _table._owner.MakeDirty();

      return editValue;
    }
  }

  internal class IndexColumnEditor : CollectionEditor
  {
    Index _index;
    bool _cancel = false;
    object[] _items;




    public IndexColumnEditor() : base(typeof(List<IndexColumn>))
    {
    }



















    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
      _index = context.Instance as Index;
      _items = null;
      _cancel = false;
      return base.EditValue(context, provider, value);
    }

    protected override object CreateInstance(Type itemType)
    {
      if (itemType == typeof(IndexColumn))
      {
        return new IndexColumn(_index, null);
      }
      throw new NotSupportedException();
    }

    protected override void CancelChanges()
    {
      _cancel = true;
    }

    protected override object[] GetItems(object editValue)
    {
      if (_items == null)
      {
        List<IndexColumn> value = editValue as List<IndexColumn>;
        _items = new object[value.Count];

        for (int n = 0; n < _items.Length; n++)


          _items[n] = value[n].Clone();



      }
      return _items;
    }

    protected override object SetItems(object editValue, object[] value)
    {



      if (editValue != null)
      {
        int length = this.GetItems(editValue).Length;
        int num2 = value.Length;
        if (!(editValue is IList))
        {
          return editValue;
................................................................................
        IList list = (IList)editValue;
        list.Clear();
        for (int i = 0; i < value.Length; i++)
        {
          IndexColumn idx = value[i] as IndexColumn;

          if (idx != null && String.IsNullOrEmpty(idx.Column) == false)

            list.Add(value[i]);

        }
      }

      if (_cancel == false)
      {
        if (_index.Columns.Count > 0 && String.IsNullOrEmpty(_index._name) == true)
          _index.Name = _index.Name;

        _index.Table._owner.MakeDirty();
      }

      return editValue;
    }
  }

  internal class IndexTypeConverter : TypeConverter
  {
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
................................................................................
        string separator = "";
        foreach (IndexColumn c in (List<IndexColumn>)value)
        {
          builder.AppendFormat("{0}[{1}]", separator, c.Column);
          if (c.SortMode != ColumnSortMode.Ascending)
            builder.Append(" DESC");
          if (c.Collate != "BINARY")
            builder.AppendFormat(" COLLATE {0}", c.Collate);

          separator = ", ";
        }
        return builder.ToString();
      }
      else
        return base.ConvertTo(context, culture, value, destinationType);
................................................................................
    Ascending = 0,
    Descending = 1
  }

  [DefaultProperty("Column")]
  internal class IndexColumn : IHaveConnectionScope, ICloneable
  {
    private Index _parent;
    private string _column;
    private ColumnSortMode _mode = ColumnSortMode.Ascending;
    private string _collate = "BINARY";

    [Editor(typeof(ColumnsTypeEditor), typeof(UITypeEditor))]
    [DisplayName("Base Column")]




    public string Column
    {
      get { return _column; }




      set { _column = value; }



    }

    [DefaultValue(ColumnSortMode.Ascending)]




    public ColumnSortMode SortMode
    {
      get { return _mode; }




      set { _mode = value; }



    }

    [DefaultValue("BINARY")]





    public string Collate
    {
      get { return _collate; }
      set
      {
        if (String.IsNullOrEmpty(value)) _collate = "BINARY";



        else _collate = value;

















      }
    }

    public override string ToString()
    {
      if (String.IsNullOrEmpty(_column) == true) return "(none)";
      return _column;
................................................................................
    }

    internal IndexColumn(Index parent, DataRow row)
    {
      _parent = parent;
      if (row != null)
      {
        _column = row["COLUMN_NAME"].ToString(); //.Trim().TrimStart('[').TrimEnd(']')
        if (row.IsNull("SORT_MODE") == false && (string)row["SORT_MODE"] != "ASC")
          _mode = ColumnSortMode.Descending;

        if (row.IsNull("COLLATION_NAME") == false && (string)row["COLLATION_NAME"] != "BINARY")
          _collate = row["COLLATION_NAME"].ToString();
      }
    }

    public object Clone()
    {
      return new IndexColumn(this);
    }
................................................................................
    private Table _table;
    internal string _name = null;
    private bool _unique;
    private List<IndexColumn> _columns = new List<IndexColumn>();
    private string _definition;
    private bool _calcname;
    internal ConflictEnum _conflict = ConflictEnum.Abort;


    protected Index(Index source)
    {
      _table = source._table;
      _name = source._name;
      _unique = source._unique;
      _columns = source._columns;
      _definition = source._definition;
      _conflict = source._conflict;








    }

    internal Index(DbConnection cnn, Table table, DataRow index)
    {
      _table = table;
      if (index != null)
      {
................................................................................
        _definition = index["INDEX_DEFINITION"].ToString();

        using (DataTable tbl = cnn.GetSchema("IndexColumns", new string[] { table.Catalog, null, table.Name, Name }))
        {
          foreach (DataRow row in tbl.Rows)
          {
            _columns.Add(new IndexColumn(this, row));
            //builder.AppendFormat("{0}[{1}]", separator, row["COLUMN_NAME"]);
            //if (row.IsNull("SORT_MODE") == false && (string)row["SORT_MODE"] != "ASC")
            //  builder.AppendFormat(" {0}", row["SORT_MODE"]);

            //if (row.IsNull("COLLATION_NAME") == false && (string)row["COLLATION_NAME"] != "BINARY")
            //  builder.AppendFormat(" COLLATE {0}", row["COLLATION_NAME"]);

            //separator = ", ";
          }
        }
      }
    }

    [DisplayName("Index Type")]


    public virtual IndexTypeEnum IndexType
    {
      get { return IndexTypeEnum.Index; }
    }

    #region IHaveConnection Members

................................................................................
    internal virtual void WriteSql(StringBuilder builder)
    {
      string separator = "";
      builder.AppendFormat("CREATE {0}INDEX [{1}].[{2}] ON [{3}] (", (_unique == true) ? "UNIQUE " : "", _table.Catalog, Name, _table.Name);
      foreach (IndexColumn c in Columns)
      {
        builder.AppendFormat("{0}[{1}]", separator, c.Column);

        if (c.SortMode != ColumnSortMode.Ascending)
          builder.Append(" DESC");
        if (c.Collate != "BINARY")


          builder.AppendFormat(" COLLATE {0}", c.Collate);

        separator = ", ";
      }
      builder.AppendFormat(");");
    }

    [Browsable(false)]
................................................................................
    }

    [Browsable(false)]
    public string OriginalSql
    {
      get { return _definition; }
    }

















    [DefaultValue(false)]

    public virtual bool Unique
    {
      get { return _unique; }




      set { _unique = value; }



    }

    [Browsable(false)]
    protected virtual string NamePrefix
    {
      get { return "IX"; }
    }
................................................................................
    protected virtual string NewName
    {
      get { return "NewIndex"; }
    }

    [ParenthesizePropertyName(true)]
    [RefreshProperties(RefreshProperties.All)]


    public virtual string Name
    {
      get
      {
        if (String.IsNullOrEmpty(_name))
        {
          if (_calcname == true) return GetHashCode().ToString();
................................................................................
            }
          }
          _calcname = false;
          return proposed;
        }
        return _name;
      }




      set { _name = value; }



    }

    [TypeConverter(typeof(IndexTypeConverter))]
    [Editor(typeof(IndexColumnEditor), typeof(UITypeEditor))]
    [RefreshProperties(RefreshProperties.All)]



    public List<IndexColumn> Columns
    {
      get { return _columns; }
    }

    #region ICloneable Members

................................................................................
    {
      return UITypeEditorEditStyle.DropDown;
    }

    override public object EditValue(ITypeDescriptorContext ctx, IServiceProvider provider, object value)
    {
      Index idx = ctx.Instance as Index;



      Table parent = idx.Table;


      // initialize editor service
      _edSvc = (System.Windows.Forms.Design.IWindowsFormsEditorService)provider.GetService(typeof(System.Windows.Forms.Design.IWindowsFormsEditorService));
      if (_edSvc == null)
        return value;

      if (value == null) value = String.Empty;
      if (String.IsNullOrEmpty(value.ToString()) == true) value = String.Empty;

      string[] values = value.ToString().Split(',');
      
      // populate the list
      _list.Items.Clear();





      using (DataTable tbl = parent._connection.GetSchema("Columns", new string[] { parent.Catalog, null, parent.Name }))

      {





        foreach (DataRow item in tbl.Rows)
        {
          // add this item with the proper check state
          CheckState check = CheckState.Unchecked;
          for (int n = 0; n < values.Length; n++)
          {
            if (values[n].Trim() == String.Format("[{0}]", item["COLUMN_NAME"].ToString()))
            {
              check = CheckState.Checked;
              break;
            }
          }
          _list.Items.Add(item["COLUMN_NAME"].ToString(), check);
        }
      }




      _list.Height = Math.Min(300, (_list.Items.Count + 1) * _list.Font.Height);

      // show the list
      _cancel = false;
      _edSvc.DropDownControl(_list);

      // build return value from checked items on the list
>
>
>
>
>
>
>
>
>
|
|
|
|
|
|
|
|
|
|

<
<



|
|
>
>







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<









>

>

>
|
>

>
>
|
|
>
>
>



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


>
>
>
>
>
>







 







>
>




>
>
|
>
>
>




|









<

>
>
>




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





|












<
<
<
<
<






>

>
>
|
>
>
>






>
>
>







 







>

>



|



|
<
<
<







 







|







 







|






>
>
>
>



>
>
>
>
|
>
>
>



>
>
>
>



>
>
>
>
|
>
>
>



>
>
>
>
>





|
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|



|
|







 







>






<


>
>
>
>
>
>
>
>







 







<
<
<
<
<
<
<
<






>
>







 







>


<
>
>
|







 








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>



>
>
>
>
|
>
>
>







 







>
>







 







>
>
>
>
|
>
>
>





>
>
>







 







>
>
>
|
>













>
>
>
>
>
|
>
|
>
>
>
>
>






|





|


>
>
>
>







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
...
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
...
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
...
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
...
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
...
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
...
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
...
480
481
482
483
484
485
486








487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
...
509
510
511
512
513
514
515
516
517
518

519
520
521
522
523
524
525
526
527
528
...
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
...
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
...
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
...
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
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer.Design
{
  using System;
  using System.Collections.Generic;
  using System.Collections;
  using System.Text;
  using System.ComponentModel;
  using System.Data;
  using System.Data.Common;
  using System.ComponentModel.Design;
  using System.Drawing.Design;
  using System.Windows.Forms;



  internal class IndexEditor : CollectionEditor
  {
    Table _table;
    CollectionEditor.CollectionForm _form;
    object[] _items = null;
    object[] _orig;
    int _count;

    internal IndexEditor(Table parent)
      : base(typeof(List<Index>))
    {
      _table = parent;
    }




















    protected override object[] GetItems(object editValue)
    {
      if (_items == null)
      {
        List<Index> value = editValue as List<Index>;

        int extra = (_table.PrimaryKey.Columns.Count > 0) ? 1 : 0;

        _items = new object[value.Count + extra];
        _orig = new object[_items.Length];
        for (int n = extra; n < _items.Length; n++)
        {
          _items[n] = ((ICloneable)value[n - extra]).Clone();
          _orig[n] = value[n - extra];
        }

        if (extra > 0)
        {
          _items[0] = ((ICloneable)_table.PrimaryKey).Clone();
          _orig[0] = _table.PrimaryKey;
        }

        _count = _items.Length;
      }
      return _items;
    }

    protected override CollectionEditor.CollectionForm CreateCollectionForm()
    {
      _form = base.CreateCollectionForm();
      _form.Text = "Index Editor";

      /* Doing this because I can't figure out how to get the Columns collection editor to notify this editor when a column of an index is updated.
         This forces the collection editor form to be "dirty" which calls SetItems() when you hit OK or cancel.  Otherwise, if you
         change a column around and hit OK, then hit OK on this editor, it won't be dirty and won't update. */
      try
      {
        _form.GetType().InvokeMember("dirty", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetField, null, _form, new object[] { true });
      }
      catch
      {
      }

      foreach (Control c in _form.Controls[0].Controls)
      {
        PropertyGrid grid = c as PropertyGrid;
        if (grid != null)
        {
          grid.HelpVisible = true;
          break;
        }
      }
      _form.Width = (int)(_form.Width * 1.25);
      _form.Height = (int)(_form.Height * 1.25);

      return _form;
    }

    protected override object CreateInstance(Type itemType)
    {
      if (itemType == typeof(Index))
      {
        return new Index(null, _table, null);
      }
      throw new NotSupportedException();
    }

    protected override bool CanRemoveInstance(object value)
    {
      return !(value is PrimaryKey);
    }

    protected override object SetItems(object editValue, object[] value)
    {
      bool dirty = false;
      int count = 0;

      if (_form.DialogResult == DialogResult.Cancel)
        value = _orig;

      if (editValue != null)
      {
        int length = this.GetItems(editValue).Length;
        int num2 = value.Length;
        if (!(editValue is IList))
        {
          return editValue;
................................................................................
        for (int i = 0; i < value.Length; i++)
        {
          Index idx = value[i] as Index;

          if (idx is PrimaryKey)
          {
            _table.PrimaryKey = (PrimaryKey)idx;
            if (idx.IsDirty) dirty = true;
            count++;
          }
          else
          {
            if (idx != null && idx.Columns.Count > 0)
            {
              idx.Name = idx.Name;
              list.Add(idx);
              if (idx.IsDirty) dirty = true;
              count++;
            }
          }
        }
      }

      if ((dirty == true || count != _count) && _form.DialogResult == DialogResult.OK)
        _table._owner.MakeDirty();

      return editValue;
    }
  }

  internal class IndexColumnEditor : CollectionEditor
  {
    Index _index;

    object[] _items;
    object[] _orig;
    int _count;
    CollectionEditor.CollectionForm _form;

    public IndexColumnEditor() : base(typeof(List<IndexColumn>))
    {
    }

    protected override CollectionEditor.CollectionForm CreateCollectionForm()
    {
      _form = base.CreateCollectionForm();
      _form.Text = "Index Columns Editor";
      foreach (Control c in _form.Controls[0].Controls)
      {
        PropertyGrid grid = c as PropertyGrid;
        if (grid != null)
        {
          grid.HelpVisible = true;
          break;
        }
      }
      _form.Width = (int)(_form.Width * 1.25);
      _form.Height = (int)(_form.Height * 1.25);
      return _form;
    }

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
      _index = context.Instance as Index;
      _items = null;
      _count = 0;
      return base.EditValue(context, provider, value);
    }

    protected override object CreateInstance(Type itemType)
    {
      if (itemType == typeof(IndexColumn))
      {
        return new IndexColumn(_index, null);
      }
      throw new NotSupportedException();
    }






    protected override object[] GetItems(object editValue)
    {
      if (_items == null)
      {
        List<IndexColumn> value = editValue as List<IndexColumn>;
        _items = new object[value.Count];
        _orig = new object[value.Count];
        for (int n = 0; n < _items.Length; n++)
        {
          _items[n] = ((ICloneable)value[n]).Clone();
          _orig[n] = value[n];
        }

        _count = _items.Length;
      }
      return _items;
    }

    protected override object SetItems(object editValue, object[] value)
    {
      if (_form.DialogResult == DialogResult.Cancel)
        value = _orig;

      if (editValue != null)
      {
        int length = this.GetItems(editValue).Length;
        int num2 = value.Length;
        if (!(editValue is IList))
        {
          return editValue;
................................................................................
        IList list = (IList)editValue;
        list.Clear();
        for (int i = 0; i < value.Length; i++)
        {
          IndexColumn idx = value[i] as IndexColumn;

          if (idx != null && String.IsNullOrEmpty(idx.Column) == false)
          {
            list.Add(value[i]);
          }
        }
      }

      if ((_index.IsDirty || _index.Columns.Count != _count) && _form.DialogResult == DialogResult.OK)
      {
        if (_index.Columns.Count > 0 && String.IsNullOrEmpty(_index._name) == true)
          _index.Name = _index.Name;
      }



      return editValue;
    }
  }

  internal class IndexTypeConverter : TypeConverter
  {
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
................................................................................
        string separator = "";
        foreach (IndexColumn c in (List<IndexColumn>)value)
        {
          builder.AppendFormat("{0}[{1}]", separator, c.Column);
          if (c.SortMode != ColumnSortMode.Ascending)
            builder.Append(" DESC");
          if (c.Collate != "BINARY")
            builder.AppendFormat(" COLLATE {0}", c.Collate.ToUpperInvariant());

          separator = ", ";
        }
        return builder.ToString();
      }
      else
        return base.ConvertTo(context, culture, value, destinationType);
................................................................................
    Ascending = 0,
    Descending = 1
  }

  [DefaultProperty("Column")]
  internal class IndexColumn : IHaveConnectionScope, ICloneable
  {
    internal Index _parent;
    private string _column;
    private ColumnSortMode _mode = ColumnSortMode.Ascending;
    private string _collate = "BINARY";

    [Editor(typeof(ColumnsTypeEditor), typeof(UITypeEditor))]
    [DisplayName("Base Column")]
    [Category("Source")]
    [Description("The column name to be included in the index.")]
    [NotifyParentProperty(true)]
    [RefreshProperties(RefreshProperties.All)]
    public string Column
    {
      get { return _column; }
      set
      {
        if (_column != value)
        {
          _column = value;
          _parent.MakeDirty();
        }
      }
    }

    [DefaultValue(ColumnSortMode.Ascending)]
    [Category("Constraints")]
    [Description("Specifies what order to sort the column in.  Descending indexes are not supported when using the SQLite legacy file format.")]
    [NotifyParentProperty(true)]
    [RefreshProperties(RefreshProperties.All)]
    public ColumnSortMode SortMode
    {
      get { return _mode; }
      set
      {
        if (value != _mode)
        {
          _mode = value;
          _parent.MakeDirty();
        }
      }
    }

    [DefaultValue("BINARY")]
    [Category("Constraints")]
    [Editor(typeof(CollationTypeEditor), typeof(UITypeEditor))]
    [Description("The collation sequence to use to generate the index for the specified column.")]
    [NotifyParentProperty(true)]
    [RefreshProperties(RefreshProperties.All)]
    public string Collate
    {
      get { return _collate; }
      set
      {
        if (String.IsNullOrEmpty(value)) value = "BINARY";

        if (value != _collate)
        {
          _collate = value;
          if (_parent is PrimaryKey)
          {
            PrimaryKey pk = _parent as PrimaryKey;
            if (pk.Columns.Count == 1)
            {
              foreach (Column c in pk.Table.Columns)
              {
                if (string.Compare(c.ColumnName, Column, StringComparison.OrdinalIgnoreCase) == 0)
                {
                  c.Collate = value;
                  break;
                }
              }
            }
          }
          _parent.MakeDirty();
        }
      }
    }

    public override string ToString()
    {
      if (String.IsNullOrEmpty(_column) == true) return "(none)";
      return _column;
................................................................................
    }

    internal IndexColumn(Index parent, DataRow row)
    {
      _parent = parent;
      if (row != null)
      {
        _column = row["COLUMN_NAME"].ToString();
        if (row.IsNull("SORT_MODE") == false && (string)row["SORT_MODE"] != "ASC")
          _mode = ColumnSortMode.Descending;

        if (row.IsNull("COLLATION_NAME") == false)
          _collate = row["COLLATION_NAME"].ToString().ToUpperInvariant();
      }
    }

    public object Clone()
    {
      return new IndexColumn(this);
    }
................................................................................
    private Table _table;
    internal string _name = null;
    private bool _unique;
    private List<IndexColumn> _columns = new List<IndexColumn>();
    private string _definition;
    private bool _calcname;
    internal ConflictEnum _conflict = ConflictEnum.Abort;
    bool _dirty = false;

    protected Index(Index source)
    {
      _table = source._table;
      _name = source._name;
      _unique = source._unique;

      _definition = source._definition;
      _conflict = source._conflict;
      _dirty = source._dirty;

      foreach (IndexColumn c in source._columns)
      {
        IndexColumn copy = ((ICloneable)c).Clone() as IndexColumn;
        copy._parent = this;
        _columns.Add(copy);
      }
    }

    internal Index(DbConnection cnn, Table table, DataRow index)
    {
      _table = table;
      if (index != null)
      {
................................................................................
        _definition = index["INDEX_DEFINITION"].ToString();

        using (DataTable tbl = cnn.GetSchema("IndexColumns", new string[] { table.Catalog, null, table.Name, Name }))
        {
          foreach (DataRow row in tbl.Rows)
          {
            _columns.Add(new IndexColumn(this, row));








          }
        }
      }
    }

    [DisplayName("Index Type")]
    [Category("Storage")]
    [Description("Specifies whether this is an index or a primary key.")]
    public virtual IndexTypeEnum IndexType
    {
      get { return IndexTypeEnum.Index; }
    }

    #region IHaveConnection Members

................................................................................
    internal virtual void WriteSql(StringBuilder builder)
    {
      string separator = "";
      builder.AppendFormat("CREATE {0}INDEX [{1}].[{2}] ON [{3}] (", (_unique == true) ? "UNIQUE " : "", _table.Catalog, Name, _table.Name);
      foreach (IndexColumn c in Columns)
      {
        builder.AppendFormat("{0}[{1}]", separator, c.Column);
        
        if (c.SortMode != ColumnSortMode.Ascending)
          builder.Append(" DESC");


        if (String.IsNullOrEmpty(c.Collate) && String.Compare(c.Collate,"BINARY", StringComparison.OrdinalIgnoreCase) != 0)
          builder.AppendFormat(" COLLATE {0}", c.Collate.ToUpperInvariant());

        separator = ", ";
      }
      builder.AppendFormat(");");
    }

    [Browsable(false)]
................................................................................
    }

    [Browsable(false)]
    public string OriginalSql
    {
      get { return _definition; }
    }

    internal void MakeDirty()
    {
      _dirty = true;
    }

    [Browsable(false)]
    internal bool IsDirty
    {
      get { return _dirty; }
    }

    internal void ClearDirty()
    {
      _dirty = false;
    }

    [DefaultValue(false)]
    [Description("When set to true, the combination of column(s) of the index must be a unique value.")]
    public virtual bool Unique
    {
      get { return _unique; }
      set
      {
        if (value != _unique)
        {
          _unique = value;
          MakeDirty();
        }
      }
    }

    [Browsable(false)]
    protected virtual string NamePrefix
    {
      get { return "IX"; }
    }
................................................................................
    protected virtual string NewName
    {
      get { return "NewIndex"; }
    }

    [ParenthesizePropertyName(true)]
    [RefreshProperties(RefreshProperties.All)]
    [Category("Identity")]
    [Description("The name of the index.")]
    public virtual string Name
    {
      get
      {
        if (String.IsNullOrEmpty(_name))
        {
          if (_calcname == true) return GetHashCode().ToString();
................................................................................
            }
          }
          _calcname = false;
          return proposed;
        }
        return _name;
      }
      set
      {
        if (value != _name)
        {
          _name = value;
          MakeDirty();
        }
      }
    }

    [TypeConverter(typeof(IndexTypeConverter))]
    [Editor(typeof(IndexColumnEditor), typeof(UITypeEditor))]
    [RefreshProperties(RefreshProperties.All)]
    [Category("Source")]
    [Description("The column(s) to be indexed.")]
    [NotifyParentProperty(true)]
    public List<IndexColumn> Columns
    {
      get { return _columns; }
    }

    #region ICloneable Members

................................................................................
    {
      return UITypeEditorEditStyle.DropDown;
    }

    override public object EditValue(ITypeDescriptorContext ctx, IServiceProvider provider, object value)
    {
      Index idx = ctx.Instance as Index;
      Trigger trig = ctx.Instance as Trigger;
      ViewTableBase parent = null;

      if (idx != null) parent = idx.Table;
      else if (trig != null) parent = trig.ViewTableBase;

      // initialize editor service
      _edSvc = (System.Windows.Forms.Design.IWindowsFormsEditorService)provider.GetService(typeof(System.Windows.Forms.Design.IWindowsFormsEditorService));
      if (_edSvc == null)
        return value;

      if (value == null) value = String.Empty;
      if (String.IsNullOrEmpty(value.ToString()) == true) value = String.Empty;

      string[] values = value.ToString().Split(',');
      
      // populate the list
      _list.Items.Clear();
      DataTable tbl = null;

      try
      {
        string prefix = "";
        tbl = parent.GetConnection().GetSchema("Columns", new string[] { parent.Catalog, null, parent.Name });
        if (tbl.Rows.Count == 0)
        {
          tbl.Dispose();
          tbl = null;
          prefix = "VIEW_";
          tbl = parent.GetConnection().GetSchema("ViewColumns", new string[] { parent.Catalog, null, parent.Name });
        }
        foreach (DataRow item in tbl.Rows)
        {
          // add this item with the proper check state
          CheckState check = CheckState.Unchecked;
          for (int n = 0; n < values.Length; n++)
          {
            if (values[n].Trim() == String.Format("[{0}]", item[prefix + "COLUMN_NAME"].ToString()))
            {
              check = CheckState.Checked;
              break;
            }
          }
          _list.Items.Add(item[prefix + "COLUMN_NAME"].ToString(), check);
        }
      }
      finally
      {
        if (tbl != null) tbl.Dispose();
      }
      _list.Height = Math.Min(300, (_list.Items.Count + 1) * _list.Font.Height);

      // show the list
      _cancel = false;
      _edSvc.DropDownControl(_list);

      // build return value from checked items on the list

Changes to SQLite.Designer/Design/PrimaryKey.cs.

1
2
3
4
5
6
7
8
9







10
11
12
13
14
15
16
..
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
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Data.Common;

namespace SQLite.Designer.Design
{







  internal class PrimaryKey : Index, ICloneable
  {
    private bool _autoincrement;

    internal PrimaryKey(DbConnection cnn, Table table, DataRow row)
      : base(cnn, table, row)
    {
................................................................................
      {
        base.Unique = true;
      }
    }

    [DefaultValue(ConflictEnum.Abort)]
    [DisplayName("On Conflict")]


    public ConflictEnum Conflict
    {
      get { return _conflict; }




      set { _conflict = value; }



    }

    [DefaultValue(false)]


    public bool AutoIncrement
    {
      get
      {
        if (Columns.Count > 1) return false;
        if (Columns.Count == 1 && Columns[0].SortMode != ColumnSortMode.Ascending) return false;
        return _autoincrement;
      }




      set { _autoincrement = value; }



    }

    #region ICloneable Members

    object ICloneable.Clone()
    {
      return new PrimaryKey(this);
    }

    #endregion
  }
}
|
|
|
|
|
|



>
>
>
>
>
>
>







 







>
>



>
>
>
>
|
>
>
>



>
>








>
>
>
>
|
>
>
>












1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
..
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
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer.Design
{
  using System;
  using System.Collections.Generic;
  using System.Text;
  using System.ComponentModel;
  using System.Data;
  using System.Data.Common;

  internal class PrimaryKey : Index, ICloneable
  {
    private bool _autoincrement;

    internal PrimaryKey(DbConnection cnn, Table table, DataRow row)
      : base(cnn, table, row)
    {
................................................................................
      {
        base.Unique = true;
      }
    }

    [DefaultValue(ConflictEnum.Abort)]
    [DisplayName("On Conflict")]
    [Category("Constraints")]
    [Description("Specifies what action to take when the primary key constraint is violated.")]
    public ConflictEnum Conflict
    {
      get { return _conflict; }
      set
      {
        if (value != _conflict)
        {
          _conflict = value;
          MakeDirty();
        }
      }
    }

    [DefaultValue(false)]
    [Category("Constraints")]
    [Description("Can only be enabled for a single column primary key of type INTEGER.  When set, the primary key is guaranteed to increment in sequence, and no previously deleted or uncommitted values will ever be used.")]
    public bool AutoIncrement
    {
      get
      {
        if (Columns.Count > 1) return false;
        if (Columns.Count == 1 && Columns[0].SortMode != ColumnSortMode.Ascending) return false;
        return _autoincrement;
      }
      set
      {
        if (value != _autoincrement)
        {
          _autoincrement = value;
          MakeDirty();
        }
      }
    }

    #region ICloneable Members

    object ICloneable.Clone()
    {
      return new PrimaryKey(this);
    }

    #endregion
  }
}

Added SQLite.Designer/Design/SimpleTokenizer.cs.





























































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer.Design
{
  using System;
  using System.Collections.Generic;
  using System.Text;

  internal static class SimpleTokenizer
  {
    public struct StringParts
    {
      internal string value;
      internal int position;
      internal string quote;
      internal bool sep;
      internal int depth;
      internal string keyword;
      internal char sepchar;

      public override string ToString()
      {
        return String.Format("{0} {1} at {2} {3} depth {4}", value, quote, position, sep == true ? "(sep)" : "", depth);
      }
    }

    public static StringParts[] BreakString(string source)
    {
      char[] opens = new char[] { '\"', '[', '\'', '(', ')', ',', ' ', ';', '\r', '\n', '\t' };
      char[] opens2 = new char[] { '\"', '[', '\'', '(', ')', ',', ' ', ';', '\r', '\n', '\t', '.' };
      char[] closes = new char[] { '\"', ']', '\'', };
      string sep = ";,";
      string opensstr = "\"['";

      if (String.IsNullOrEmpty(source) == true) return new StringParts[0];

      int n = 0;
      int x;
      int depth = 0;
      List<StringParts> ls = new List<StringParts>();
      int startat = 0;

      while (source.Length > 0)
      {
        if (source.Length > 1 && source[0] == '-' && source[1] == '-')
        {
          StringParts tok = new StringParts();
          tok.position = startat;
          x = source.IndexOf('\n');
          if (x == -1) tok.value = source;
          else tok.value = source.Substring(0, x + 1);

          //ls.Add(tok);
          source = source.Substring(tok.value.Length);
          startat += tok.value.Length;
          continue;
        }
        else if (source.Length > 1 && source[0] == '/' && source[1] == '*')
        {
          StringParts tok = new StringParts();
          tok.position = startat;
          x = source.IndexOf("*/");
          if (x == -1) tok.value = source;
          else tok.value = source.Substring(0, x + 2);

          //ls.Add(tok);
          source = source.Substring(tok.value.Length);
          startat += tok.value.Length;
          continue;
        }
        int comment = source.IndexOf("--", n);
        if (comment == -1) comment = source.IndexOf("/*", n);

        if (n > 0)
          n = source.IndexOfAny(opens2, n);
        else
          n = source.IndexOfAny(opens, n);

        if (comment > -1 && (n == -1 || comment < n))
          n = comment;

        if (n == -1) break;

        x = opensstr.IndexOf(source[n]);
        if (x != -1)
        {
          while (n != -1)
          {
            n = source.IndexOf(closes[x], n + 1);
            if (n == -1)
              break;

            if (n < source.Length - 1 && source[n + 1] == source[n])
            {
              startat++;
              source = source.Remove(n, 1);
            }
            else
            {
              n++;
              break;
            }
          }
          if (n == -1)
            break;
        }
        else
        {
          StringParts tok = new StringParts();

          int y = sep.IndexOf(source[n]);
          tok.sep = (y != -1);
          tok.sepchar = (y != -1) ? sep[y] : '\0';

          if (source[n] == '(') depth++;
          tok.depth = depth;
          if (source[n] == ')') depth--;

          tok.value = source.Substring(0, n);
          tok.position = startat;

          if (tok.value.Length > 1)
          {
            x = opensstr.IndexOf(tok.value[0]);
            if (x != -1 && tok.value[tok.value.Length - 1] == closes[x])
            {
              tok.quote = String.Format("{0}{1}", tok.value[0], tok.value[tok.value.Length - 1]);
              tok.value = tok.value.Substring(1, tok.value.Length - 2);
            }
            else
              tok.keyword = tok.value.ToUpperInvariant();
          }

          if (source.Length - n > 1 && ((source[n] == '-' && source[n + 1] == '-') || source[n] == '/' && source[n + 1] == '*'))
          {
            startat += n;
            source = source.Substring(n);
          }
          else
          {
            startat += (n + 1);
            source = source.Substring(n + 1);
          }
          if (tok.value.Length > 0)
            ls.Add(tok);
          else if (ls.Count > 0 && tok.sep)
          {
            StringParts prev = ls[ls.Count - 1];
            ls.RemoveAt(ls.Count - 1);
            prev.sep = tok.sep;
            prev.sepchar = tok.sepchar;
            ls.Add(prev);
          }
          n = 0;
        }
      }

      if (source.Length > 0)
      {
        StringParts tok = new StringParts();

        tok.value = source.Trim();
        tok.position = startat;

        if (tok.value.Length > 1)
        {
          x = opensstr.IndexOf(tok.value[0]);
          if (x != -1 && tok.value[tok.value.Length - 1] == closes[x])
          {
            tok.quote = String.Format("{0}{1}", tok.value[0], tok.value[tok.value.Length - 1]);
            tok.value = tok.value.Substring(1, tok.value.Length - 2);
          }
          else
            tok.keyword = tok.value.ToUpperInvariant();
        }
        if (tok.value.Length > 0) ls.Add(tok);
      }

      StringParts[] ar = new StringParts[ls.Count];
      ls.CopyTo(ar, 0);

      return ar;
    }
  }
}

Changes to SQLite.Designer/Design/Table.cs.








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
..
56
57
58
59
60
61
62





63
64
65
66
67
68
69
..
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
...
135
136
137
138
139
140
141












142
143
144
145
146
147
148
...
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
...
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
...
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
...
380
381
382
383
384
385
386















387
388
389
390
391
392
393







namespace SQLite.Designer.Design
{
  using System;
  using System.Data.Common;
  using System.ComponentModel.Design;
  using System.ComponentModel;
  using System.Drawing.Design;
  using System.Collections.Generic;
  using System.Data;
  using System.Text;
  using SQLite.Designer.Editors;










  internal class Table : ICustomTypeDescriptor, IHaveConnection
  {
    private string _name;
    private string _oldname;
    private string _catalog;
    private List<Column> _columns = new List<Column>();
    private bool _exists = false;
    private bool _hascheck = false;
    private string _origSql = String.Empty;
    private List<Index> _indexes = new List<Index>();
    private List<Index> _oldindexes = new List<Index>();
    private List<ForeignKey> _fkeys = new List<ForeignKey>();
    private List<ForeignKey> _oldfkeys = new List<ForeignKey>();



    private PrimaryKey _key;
    internal TableDesignerDoc _owner;
    internal DbConnection _connection;

    internal Table(string tableName, DbConnection connection, TableDesignerDoc owner)
    {
      _owner = owner;
................................................................................
      {
        foreach (DataRow row in tbl.Rows)
        {
          _columns.Add(new Column(row, this));
        }
      }
    }






    private void ReloadDefinition()
    {
      using (DataTable tbl = _connection.GetSchema("Tables", new string[] { Catalog, null, Name }))
      {
        if (tbl.Rows.Count > 0)
        {
................................................................................
          else if (_key == null)
          {
            _key = new PrimaryKey(_connection, this, row);
          }
        }
      }


      StringBuilder builder = new StringBuilder();


























































      builder.Append(_origSql);

      builder.AppendLine(";");
      foreach (Index idx in _oldindexes)
      {
        builder.AppendFormat("{0};\r\n", idx.OriginalSql);
      }
















      _origSql = builder.ToString();
    }

    internal void Committed()
    {
      _exists = true;
      ReloadDefinition();












    }

    [Browsable(false)]
    public List<Index> Indexes
    {
      get { return _indexes; }
    }
................................................................................
    }

    [Browsable(false)]
    public List<ForeignKey> ForeignKeys
    {
      get { return _fkeys; }
    }













    [Browsable(false)]
    public string OriginalSql
    {
      get { return _origSql; }
    }

................................................................................
    {
      get { return _hascheck; }
    }

    [Category("Storage")]
    [RefreshProperties(RefreshProperties.All)]
    [ParenthesizePropertyName(true)]
    public string Name
    {
      get { return _name; }
      set
      {
        if (_name != value)
        {
          _name = value;
................................................................................
      return String.Format("[{0}].[{1}]", Catalog, Name);
    }

    [Category("Storage")]
    [Editor(typeof(CatalogTypeEditor), typeof(UITypeEditor))]
    [DefaultValue("main")]
    [RefreshProperties(RefreshProperties.All)]
    public string Catalog
    {
      get { return _catalog; }
      //set
      //{
      //  string catalogs = "";
      //  using (DataTable table = _connection.GetSchema("Catalogs"))
      //  {
      //    foreach (DataRow row in table.Rows)
      //    {
      //      catalogs += (row[0].ToString() + ",");
      //    }
      //  }

      //  if (catalogs.IndexOf(value + ",", StringComparison.OrdinalIgnoreCase) == -1)
      //    throw new ArgumentOutOfRangeException("Unrecognized catalog!");

      //  _catalog = value;
      //}
    }
    [Category("Storage")]
    public string Database
    {
      get { return _connection.DataSource; }
    }

    [Browsable(false)]
................................................................................
      string altName = null;

      if (_exists)
      {
        Guid g = Guid.NewGuid();
        altName = String.Format("{0}_{1}", Name, g.ToString("N"));




        foreach (Index idx in _oldindexes)
        {
          builder.AppendFormat("DROP INDEX [{0}].[{1}];\r\n", _catalog, idx.Name);
        }














        builder.AppendFormat("ALTER TABLE [{0}].[{1}] RENAME TO [{2}];\r\n", _catalog, _oldname, altName);
      }


      builder.AppendFormat("CREATE TABLE [{0}].[{1}] (\r\n", _catalog, Name);
      string separator = "    ";

      foreach (Column c in Columns)
      {


        builder.Append(separator);
        c.WriteSql(builder);
        separator = ",\r\n    ";

      }

      if (_key.Columns.Count > 1)
      {
        string innersep = "";
        builder.AppendFormat("{0}CONSTRAINT PK_{1} PRIMARY KEY (", separator, Name);
        foreach (IndexColumn c in _key.Columns)
        {
          builder.AppendFormat("{0}[{1}]{2}", innersep, c.Column, (c.SortMode == ColumnSortMode.Ascending) ? "" : " DESC");






          innersep = ", ";
        }
        builder.Append(")");

        if (_key.Conflict != ConflictEnum.Abort)
          builder.AppendFormat(" ON CONFLICT {0}", _key.Conflict.ToString());


















      }

      foreach (ForeignKey fkey in ForeignKeys)
      {
        builder.Append(separator);
        fkey.WriteSql(builder);
      }
................................................................................

      builder.Append("\r\n);\r\n");

      // Rebuilding an existing table
      if (altName != null)
      {
        separator = "";

        builder.AppendFormat("INSERT INTO [{0}].[{1}] (", _catalog, Name);
        foreach (Column c in Columns)
        {
          if (String.IsNullOrEmpty(c.OriginalName) == false)
          {
            builder.AppendFormat("{1}[{0}]", c.ColumnName, separator);
            separator = ", ";
          }
        }
        builder.Append(") SELECT ");
        separator = "";
        foreach (Column c in Columns)
        {
          if (String.IsNullOrEmpty(c.OriginalName) == false)
          {
            builder.AppendFormat("{1}[{0}]", c.OriginalName, separator);
            separator = ", ";
          }
        }
        builder.AppendFormat(" FROM [{0}].[{1}];\r\n", _catalog, altName);


        builder.AppendFormat("DROP TABLE [{0}].[{1}];\r\n", _catalog, altName);
      }

      separator = "";



      foreach (Index idx in _indexes)
      {
        builder.Append(separator);
        idx.WriteSql(builder);











        separator = "\r\n";


      }

      return builder.ToString();
    }

    #region IHaveConnection Members

    public DbConnection GetConnection()
    {
      return _connection;
    }

    #endregion

    #region ICustomTypeDescriptor Members

    AttributeCollection ICustomTypeDescriptor.GetAttributes()
    {
      return TypeDescriptor.GetAttributes(GetType());
    }

................................................................................
  internal interface IHaveConnectionScope : IHaveConnection
  {
    [Browsable(false)]
    string CatalogScope { get; }
    [Browsable(false)]
    string TableScope { get; }
  }
















  internal class CatalogTypeEditor : ObjectSelectorEditor
  {
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
      return UITypeEditorEditStyle.DropDown;
    }
>
>
>
>
>
>
>












>
>
>
>
>
>
>
>
>
|












>
>
>







 







>
>
>
>
>







 







>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>





>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>







 







|







 







|


<
<
<
<
<
<
<
<
<
<
|
<
<

<
<
<







 







>
>
>
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|


>





>
>
|
|
|
>





|


|
>
>
>
>
>
>





|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>









|









|

>


>
|
>
>
>
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
|
>
>





<
<
|




<
<







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
..
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
...
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
...
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
...
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
...
297
298
299
300
301
302
303
304
305
306










307


308



309
310
311
312
313
314
315
...
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
...
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
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer.Design
{
  using System;
  using System.Data.Common;
  using System.ComponentModel.Design;
  using System.ComponentModel;
  using System.Drawing.Design;
  using System.Collections.Generic;
  using System.Data;
  using System.Text;
  using SQLite.Designer.Editors;

  internal abstract class ViewTableBase: IHaveConnection
  {
    public abstract string Name { get; set; }
    public abstract string Catalog { get; }
    public abstract object Triggers { get; }
    public abstract void MakeDirty();
    public abstract DbConnection GetConnection();
  }

  internal class Table : ViewTableBase, ICustomTypeDescriptor
  {
    private string _name;
    private string _oldname;
    private string _catalog;
    private List<Column> _columns = new List<Column>();
    private bool _exists = false;
    private bool _hascheck = false;
    private string _origSql = String.Empty;
    private List<Index> _indexes = new List<Index>();
    private List<Index> _oldindexes = new List<Index>();
    private List<ForeignKey> _fkeys = new List<ForeignKey>();
    private List<ForeignKey> _oldfkeys = new List<ForeignKey>();
    private List<string> _check = new List<string>();
    private List<Trigger> _triggers = new List<Trigger>();
    private List<Trigger> _oldtriggers = new List<Trigger>();
    private PrimaryKey _key;
    internal TableDesignerDoc _owner;
    internal DbConnection _connection;

    internal Table(string tableName, DbConnection connection, TableDesignerDoc owner)
    {
      _owner = owner;
................................................................................
      {
        foreach (DataRow row in tbl.Rows)
        {
          _columns.Add(new Column(row, this));
        }
      }
    }

    public override void MakeDirty()
    {
      _owner.MakeDirty();
    }

    private void ReloadDefinition()
    {
      using (DataTable tbl = _connection.GetSchema("Tables", new string[] { Catalog, null, Name }))
      {
        if (tbl.Rows.Count > 0)
        {
................................................................................
          else if (_key == null)
          {
            _key = new PrimaryKey(_connection, this, row);
          }
        }
      }

      _check.Clear();
      StringBuilder builder = new StringBuilder();
      SimpleTokenizer.StringParts[] arr = SimpleTokenizer.BreakString(_origSql);
      for (int n = 0; n < arr.Length - 3; n++)
      {
        if (arr[n].keyword == "CONSTRAINT")
        {
          builder.Length = 0;
          int x;
          for (x = 1; x < 3; x++)
          {
            if (arr[n + x].keyword == "CHECK")
              break;
          }
          if (x == 3)
          {
            n += 2;
            continue;
          }
          x += n + 1;
          int depth = arr[n].depth;
          int basedepth = arr[x].depth;
          for (; x < arr.Length; x++)
          {
            if (arr[x].depth < basedepth)
              break;

            if (builder.Length > 0)
              builder.Append(" ");

            while (depth < arr[x].depth)
            {
              builder.Append("(");
              depth++;
            }
            while (depth > arr[x].depth)
            {
              builder.Append(")");
              depth--;
            }

            if (String.IsNullOrEmpty(arr[x].quote) == false)
              builder.Append(arr[x].quote[0]);
            builder.Append(arr[x].value);
            if (String.IsNullOrEmpty(arr[x].quote) == false)
              builder.Append(arr[x].quote[1]);

            if (arr[x].sep == true) break;
          }
          while (depth > arr[n].depth)
          {
            builder.Append(")");
            depth--;
          }
          n = x;
          _check.Add(builder.ToString());
        }
      }

      builder.Length = 0;
      builder.Append(_origSql);

      builder.AppendLine(";");
      foreach (Index idx in _oldindexes)
      {
        builder.AppendFormat("{0};\r\n", idx.OriginalSql);
      }

      _triggers.Clear();
      _oldtriggers.Clear();

      using (DataTable tbl = _connection.GetSchema("Triggers", new string[] { Catalog, null, Name }))
      {
        foreach (DataRow row in tbl.Rows)
        {
          Trigger t = new Trigger(this, row);
          _triggers.Add(t);
          _oldtriggers.Add(((ICloneable)t).Clone() as Trigger);

          builder.AppendFormat("{0};\r\n", t.OriginalSql);
        }
      }

      _origSql = builder.ToString();
    }

    internal void Committed()
    {
      _exists = true;
      ReloadDefinition();

      foreach (Column c in Columns)
        c.Committed();

      foreach (ForeignKey key in ForeignKeys)
        key.ClearDirty();

      foreach (Index idx in Indexes)
        idx.ClearDirty();

      if (PrimaryKey != null)
        PrimaryKey.ClearDirty();
    }

    [Browsable(false)]
    public List<Index> Indexes
    {
      get { return _indexes; }
    }
................................................................................
    }

    [Browsable(false)]
    public List<ForeignKey> ForeignKeys
    {
      get { return _fkeys; }
    }

    [Browsable(false)]
    public List<string> Check
    {
      get { return _check; }
    }

    [Browsable(false)]
    public override object Triggers
    {
      get { return _triggers; }
    }

    [Browsable(false)]
    public string OriginalSql
    {
      get { return _origSql; }
    }

................................................................................
    {
      get { return _hascheck; }
    }

    [Category("Storage")]
    [RefreshProperties(RefreshProperties.All)]
    [ParenthesizePropertyName(true)]
    public override string Name
    {
      get { return _name; }
      set
      {
        if (_name != value)
        {
          _name = value;
................................................................................
      return String.Format("[{0}].[{1}]", Catalog, Name);
    }

    [Category("Storage")]
    [Editor(typeof(CatalogTypeEditor), typeof(UITypeEditor))]
    [DefaultValue("main")]
    [RefreshProperties(RefreshProperties.All)]
    public override string Catalog
    {
      get { return _catalog; }










    }






    [Category("Storage")]
    public string Database
    {
      get { return _connection.DataSource; }
    }

    [Browsable(false)]
................................................................................
      string altName = null;

      if (_exists)
      {
        Guid g = Guid.NewGuid();
        altName = String.Format("{0}_{1}", Name, g.ToString("N"));

        if (_oldindexes.Count > 0)
        {
          builder.Append("-- Drop previous indexes on the table\r\n");
          foreach (Index idx in _oldindexes)
          {
            builder.AppendFormat("DROP INDEX [{0}].[{1}];\r\n", _catalog, idx.Name);
          }
          builder.AppendLine();
        }

        if (_oldtriggers.Count > 0)
        {
          builder.Append("-- Drop previous triggers on the table\r\n");
          foreach (Trigger trig in _oldtriggers)
          {
            builder.AppendFormat("DROP TRIGGER [{0}].[{1}];\r\n", _catalog, trig.Name);
          }
          builder.AppendLine();
        }

        builder.Append("-- Rename the old table\r\n");
        builder.AppendFormat("ALTER TABLE [{0}].[{1}] RENAME TO [{2}];\r\n\r\n", _catalog, _oldname, altName);
      }

      builder.Append("-- Create the new table\r\n");
      builder.AppendFormat("CREATE TABLE [{0}].[{1}] (\r\n", _catalog, Name);
      string separator = "    ";

      foreach (Column c in Columns)
      {
        if (String.IsNullOrEmpty(c.ColumnName) == false)
        {
          builder.Append(separator);
          c.WriteSql(builder);
          separator = ",\r\n    ";
        }
      }

      if (_key.Columns.Count > 1)
      {
        string innersep = "";
        builder.AppendFormat("{0}CONSTRAINT [PK_{1}] PRIMARY KEY (", separator, Name);
        foreach (IndexColumn c in _key.Columns)
        {
          builder.AppendFormat("{0}[{1}]", innersep, c.Column);
          if (String.IsNullOrEmpty(c.Collate) == false && String.Compare(c.Collate, "BINARY", StringComparison.OrdinalIgnoreCase) != 0)
            builder.AppendFormat(" COLLATE {0}", c.Collate.ToUpperInvariant());

          if (c.SortMode != ColumnSortMode.Ascending)
            builder.AppendFormat(" DESC");

          innersep = ", ";
        }
        builder.Append(")");

        if (_key.Conflict != ConflictEnum.Abort)
          builder.AppendFormat(" ON CONFLICT {0}", _key.Conflict.ToString().ToUpperInvariant());
      }

      for (int n = 0; n < Check.Count; n++)
      {
        string check = Check[n];

        if (String.IsNullOrEmpty(check) == true) continue;
        SimpleTokenizer.StringParts[] arr = SimpleTokenizer.BreakString(check);
        for (int x = 0; x < arr.Length; x++)
        {
          if (arr[x].depth == 0)
          {
            check = String.Format("({0})", check);
            break;
          }
        }
        builder.Append(separator);
        builder.AppendFormat("CONSTRAINT [CK_{0}_{1}] CHECK {2}", Name, n + 1, check);
      }

      foreach (ForeignKey fkey in ForeignKeys)
      {
        builder.Append(separator);
        fkey.WriteSql(builder);
      }
................................................................................

      builder.Append("\r\n);\r\n");

      // Rebuilding an existing table
      if (altName != null)
      {
        separator = "";
        builder.Append("\r\n-- Copy the contents of the old table into the new table\r\n");
        builder.AppendFormat("INSERT INTO [{0}].[{1}] (", _catalog, Name);
        foreach (Column c in Columns)
        {
          if (String.IsNullOrEmpty(c.OriginalName) == false)
          {
            builder.AppendFormat("{1}[{0}]", c.ColumnName, separator);
            separator = ", ";
          }
        }
        builder.Append(")\r\n  SELECT ");
        separator = "";
        foreach (Column c in Columns)
        {
          if (String.IsNullOrEmpty(c.OriginalName) == false)
          {
            builder.AppendFormat("{1}[{0}]", c.OriginalName, separator);
            separator = ", ";
          }
        }
        builder.AppendFormat("\r\n  FROM [{0}].[{1}];\r\n\r\n", _catalog, altName);

        builder.Append("-- Drop the old table\r\n");
        builder.AppendFormat("DROP TABLE [{0}].[{1}];\r\n", _catalog, altName);
      }

      separator = "\r\n";
      if (_indexes.Count > 0)
      {
        builder.Append("\r\n-- Create the new indexes");
        foreach (Index idx in _indexes)
        {
          builder.Append(separator);
          idx.WriteSql(builder);
        }
        builder.AppendLine();
      }

      if (_triggers.Count > 0)
      {
        builder.Append("\r\n-- Create the new triggers");
        foreach (Trigger trig in _triggers)
        {
          builder.Append(separator);
          trig.WriteSql(builder);
          separator = "\r\n";
        }
        builder.AppendLine();
      }

      return builder.ToString();
    }



    public override DbConnection GetConnection()
    {
      return _connection;
    }



    #region ICustomTypeDescriptor Members

    AttributeCollection ICustomTypeDescriptor.GetAttributes()
    {
      return TypeDescriptor.GetAttributes(GetType());
    }

................................................................................
  internal interface IHaveConnectionScope : IHaveConnection
  {
    [Browsable(false)]
    string CatalogScope { get; }
    [Browsable(false)]
    string TableScope { get; }
  }

  internal class CollationTypeEditor : ObjectSelectorEditor
  {
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
      return UITypeEditorEditStyle.DropDown;
    }

    protected override void FillTreeWithData(Selector selector, ITypeDescriptorContext context, IServiceProvider provider)
    {
      base.FillTreeWithData(selector, context, provider);
      selector.AddNode("BINARY", "BINARY", null);
      selector.AddNode("NOCASE", "NOCASE", null);
    }
  }

  internal class CatalogTypeEditor : ObjectSelectorEditor
  {
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
      return UITypeEditorEditStyle.DropDown;
    }

Added SQLite.Designer/Design/Trigger.cs.

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer.Design
{
  using System;
  using System.Collections.Generic;
  using System.Collections;
  using System.Text;
  using System.ComponentModel;
  using System.ComponentModel.Design;
  using System.Windows.Forms;
  using System.Drawing.Design;
  using System.Data;
  using System.Data.Common;

  public enum TriggerOccurs
  {
    Before = 0,
    After = 1,
  }
  
  public enum ViewTriggerOccurs
  {
    InsteadOf = 2
  }

  public enum TriggerType
  {
    Delete = 0,
    Insert = 1,
    Update = 2,
  }

  internal class ViewTrigger : Trigger, ICloneable
  {
    internal ViewTrigger(ViewTrigger source)
      : base(source)
    {
      _triggerOccurs = (int)ViewTriggerOccurs.InsteadOf;
    }

    internal ViewTrigger(ViewTableBase parent, DataRow row)
      : base(parent, row)
    {
      _triggerOccurs = (int)ViewTriggerOccurs.InsteadOf;
    }

    [Browsable(true)]
    [DefaultValue(ViewTriggerOccurs.InsteadOf)]
    [Category("Event")]
    [Description("Determines when the trigger fires.  For tables, Before or After are supported.  For views, Instead Of is the only option.")]
    public new ViewTriggerOccurs Occurs
    {
      get
      {
        return ViewTriggerOccurs.InsteadOf;
      }
    }

    #region ICloneable Members

    object ICloneable.Clone()
    {
      return new ViewTrigger(this);
    }

    #endregion
  }

  [DefaultProperty("SQL")]
  internal class Trigger : IHaveConnection, ICloneable
  {
    protected int _triggerOccurs;
    private TriggerType _type = TriggerType.Update;
    //private bool _eachRow;
    private string _when;
    private ViewTableBase _table;
    private string _name;
    private string _columns;
    private string _action;
    private bool _calcname;
    private string _origsql;
    private bool _dirty = false;

    protected Trigger(Trigger source)
    {
      _triggerOccurs = source._triggerOccurs;
      _type = source._type;
      //_eachRow = source._eachRow;
      _when = source._when;
      _table = source._table;
      _name = source._name;
      _columns = source._columns;
      _action = source._action;
      _dirty = source._dirty;
    }

    internal void MakeDirty()
    {
      _dirty = true;
    }

    [Browsable(false)]
    internal bool IsDirty
    {
      get { return _dirty; }
    }

    internal void ClearDirty()
    {
      _dirty = false;
    }

    internal virtual void WriteSql(StringBuilder builder)
    {
      WriteSql(builder, false);
    }

    private void WriteSql(StringBuilder builder, bool temp)
    {
      string name = Name;

      if (temp == true)
        name = String.Format("{0}_{1}", name, Guid.NewGuid().ToString("N"));

      builder.AppendFormat("CREATE TRIGGER [{0}].[{1}]", _table.Catalog, name);
      switch (_triggerOccurs)
      {
        case 0:
          builder.Append(" BEFORE");
          break;
        case 1:
          builder.Append(" AFTER");
          break;
        case 2:
          builder.Append(" INSTEAD OF");
          break;
      }

      builder.AppendFormat(" {0}", _type.ToString().ToUpperInvariant());
      if (_type == TriggerType.Update && String.IsNullOrEmpty(Columns) == false)
        builder.AppendFormat(" OF {0}", Columns);

      builder.AppendFormat(" ON [{0}].[{1}]", _table.Catalog, _table.Name);

      if (EachRow)
        builder.AppendFormat(" FOR EACH ROW");
      if (String.IsNullOrEmpty(When) == false)
        builder.AppendFormat(" WHEN {0}", When);

      builder.AppendFormat("\r\nBEGIN\r\n{0}", SQL);
      SimpleTokenizer.StringParts[] arr = SimpleTokenizer.BreakString(SQL);
      if (arr[arr.Length - 1].sepchar != ';')
        builder.Append(";");

      builder.Append("\r\nEND;");
    }

    [DefaultValue(TriggerOccurs.Before)]
    [Category("Event")]
    [Description("Determines when the trigger fires.  For tables, Before or After are supported.  For views, Instead Of is the only option.")]
    public virtual TriggerOccurs Occurs
    {
      get { return (TriggerOccurs)_triggerOccurs; }
      set
      {
        if (_triggerOccurs != (int)value)
        {
          _triggerOccurs = (int)value;
          MakeDirty();
        }
      }
    }

    [DefaultValue(TriggerType.Update)]
    [Category("Event")]
    [Description("Determines what type of operation the trigger applies to.  Can be either Insert, Update or Delete.")]
    public TriggerType Type
    {
      get { return _type; }
      set
      {
        if (_type != value)
        {
          _type = value;
          MakeDirty();
        }
      }
    }

    [DefaultValue(true)]
    [Category("Event")]
    [Description("When set to true, the trigger will fire for each row in an update, insert or delete operation.")]
    public bool EachRow
    {
      get { return true; }
      //get { return _eachRow; }
      //set { _eachRow = value; }
    }

    [Category("Constraint")]
    [Description("Limits the exection of the trigger so it only occurs when the expression evaluates to True.")]
    public string When
    {
      get { return _when; }
      set
      {
        if (_when != value)
        {
          _when = value;
          MakeDirty();
        }
      }
    }

    [Browsable(false)]
    protected virtual string NamePrefix
    {
      get { return "TRG"; }
    }

    [Browsable(false)]
    protected virtual string NewName
    {
      get { return "NewTrigger"; }
    }

    [Browsable(false)]
    internal ViewTableBase ViewTableBase
    {
      get { return _table; }
    }

    [ParenthesizePropertyName(true)]
    [Category("Identity")]
    [Description("The name of the trigger")]
    public string Name
    {
      get
      {
        if (String.IsNullOrEmpty(_name))
        {
          if (_calcname == true) return GetHashCode().ToString();

          string name = String.Format("{0}_{1}", NamePrefix, NewName);
          int count = 0;
          string proposed = name;

          _calcname = true;
          for (int n = 0; n < ((IList)_table.Triggers).Count; n++)
          {
            Trigger idx = ((IList)_table.Triggers)[n] as Trigger;
            proposed = string.Format("{0}{1}", name, (count > 0) ? count.ToString() : "");
            if (idx.Name == proposed)
            {
              count++;
              n = -1;
            }
          }
          _calcname = false;
          return proposed;
        }
        return _name;
      }
      set
      {
        if (_name != value)
        {
          _name = value;
          MakeDirty();
        }
      }
    }

    [Editor(typeof(ColumnsMultiSelectEditor), typeof(UITypeEditor))]
    [Category("Event")]
    [DisplayName("Update Columns")]
    [Description("Limit the trigger to only occur when updating these columns")]
    public string Columns
    {
      get { return _columns; }
      set
      {
        if (_columns != value)
        {
          _columns = value;
          MakeDirty();
        }
      }
    }

    [Category("Action")]
    [Description("The SQL to execute for this trigger")]
    public string SQL
    {
      get { return _action; }
      set
      {
        //using (DbTransaction trans = GetConnection().BeginTransaction())
        //using (DbCommand cmd = GetConnection().CreateCommand())
        //{
        //  StringBuilder builder = new StringBuilder();
        //  WriteSql(builder, true);
        //  cmd.CommandText = builder.ToString();

        //  cmd.ExecuteNonQuery();
        //  trans.Rollback();
        //}
        if (_action != value)
        {
          _action = value;
          MakeDirty();
        }
      }
    }

    [Browsable(false)]
    public string OriginalSql
    {
      get { return _origsql; }
    }

    internal Trigger(ViewTableBase parent, DataRow row)
    {
      _table = parent;
      if (row != null)
      {
        _name = row["TRIGGER_NAME"].ToString();

        string sql = row["TRIGGER_DEFINITION"].ToString();
        _origsql = sql;
        SimpleTokenizer.StringParts[] arr = SimpleTokenizer.BreakString(sql);

        int x = 3;
        switch (arr[x].keyword)
        {
          case "BEFORE":
            _triggerOccurs = 0;
            break;
          case "AFTER":
            _triggerOccurs = 1;
            break;
          case "INSTEAD":
            _triggerOccurs = 2;
            x++;
            break;
          default:
            x--;
            break;
        }
        x++;

        switch (arr[x].keyword)
        {
          case "UPDATE":
            _type = TriggerType.Update;
            if (arr[x + 1].keyword == "OF")
            {
              x++;
              StringBuilder builder = new StringBuilder();
              string separator = "";
              while (arr[x + 1].keyword != "ON")
              {
                builder.AppendFormat("{0}[{1}]", separator, arr[x + 1].value);
                separator = ", ";
                x++;
              }
              _columns = builder.ToString();
            }
            break;
          case "INSERT":
            _type = TriggerType.Insert;
            break;
          case "DELETE":
            _type = TriggerType.Delete;
            break;
        }
        x++;

        while (arr[x].keyword != "BEGIN")
        {
          if (arr[x].keyword == "FOR" && arr[x + 1].keyword == "EACH" && arr[x + 1].keyword == "ROW")
          {
            //_eachRow = true;
            x += 3;
            continue;
          }

          if (arr[x].keyword == "WHEN")
          {
            x++;
            int depth = 0;
            StringBuilder builder = new StringBuilder();
            while (arr[x].keyword != "BEGIN")
            {
              if (builder.Length > 0) builder.Append(" ");
              while (depth < arr[x].depth)
              {
                depth++;
                builder.Append("(");
              }
              while (depth > arr[x].depth)
              {
                depth--;
                builder.Append(")");
              }

              if (String.IsNullOrEmpty(arr[x].quote) == false)
                builder.Append(arr[x].quote[0]);
              builder.Append(arr[x].value);
              if (String.IsNullOrEmpty(arr[x].quote) == false)
                builder.Append(arr[x].quote[1]);
            }
            while (depth > 0)
            {
              depth--;
              builder.Append(")");
            }
            _when = builder.ToString();
            break;
          }
          x++;
        }

        int startpos = arr[x].position + arr[x].value.Length;

        x = arr.Length - 1;
        while (arr[x].keyword != "END")
        {
          x--;
        }
        int endpos = arr[x].position;

        _action = sql.Substring(startpos, endpos - startpos);
        _action = _action.TrimStart('\r').TrimStart('\n').TrimEnd('\n').TrimEnd('\r').Trim();
      }
    }

    #region IHaveConnection Members

    public DbConnection GetConnection()
    {
      return ((IHaveConnection)_table).GetConnection();
    }

    #endregion

    #region ICloneable Members

    object ICloneable.Clone()
    {
      return new Trigger(this);
    }

    #endregion
  }

  internal class TriggerEditor : CollectionEditor
  {
    ViewTableBase _table;
    object[] _items;
    object[] _orig;
    CollectionEditor.CollectionForm _form;
    int _count;

    internal TriggerEditor(ViewTableBase parent)
      : base((parent is View) ? typeof(List<ViewTrigger>) :  typeof(List<Trigger>))
    {
      _table = parent;
    }

    protected override CollectionEditor.CollectionForm CreateCollectionForm()
    {
      _form = base.CreateCollectionForm();
      _form.Text = "Trigger Editor";
      foreach (Control c in _form.Controls[0].Controls)
      {
        PropertyGrid grid = c as PropertyGrid;
        if (grid != null)
        {
          grid.HelpVisible = true;
          break;
        }
      }
      _form.Width = (int)(_form.Width * 1.25);
      _form.Height = (int)(_form.Height * 1.25);
      return _form;
    }

    protected override object CreateInstance(Type itemType)
    {
      if (itemType == typeof(Trigger))
      {
        return new Trigger(_table, null);
      }
      else if (itemType == typeof(ViewTrigger))
      {
        return new ViewTrigger(_table, null);
      }
      throw new NotSupportedException();
    }

    protected override object[] GetItems(object editValue)
    {
      if (_items == null)
      {
        IList value = editValue as IList;
        _items = new object[value.Count];
        _orig = new object[value.Count];
        for (int n = 0; n < _items.Length; n++)
        {
          _items[n] = ((ICloneable)value[n]).Clone();
          _orig[n] = value[n];
        }
        _count = _items.Length;
      }
      return _items;
    }

    protected override object SetItems(object editValue, object[] value)
    {
      bool dirty = false;
      if (_form.DialogResult == DialogResult.Cancel)
        value = _orig;

      if (editValue != null)
      {
        int length = this.GetItems(editValue).Length;
        int num2 = value.Length;
        if (!(editValue is IList))
        {
          return editValue;
        }
        IList list = (IList)editValue;
        list.Clear();
        for (int i = 0; i < value.Length; i++)
        {
          Trigger trig = value[i] as Trigger;

          if (trig != null && String.IsNullOrEmpty(trig.SQL) == false)
          {
            if (trig.IsDirty) dirty = true;
            trig.Name = trig.Name;
            list.Add(trig);
          }
        }

        if ((dirty == true || list.Count != _count) && _form.DialogResult == DialogResult.OK)
          _table.MakeDirty();
      }

      return editValue;
    }
  }
}

Changes to SQLite.Designer/Design/Unique.cs.

1
2
3
4
5
6
7
8
9







10
11
12
13
14
15
16
..
37
38
39
40
41
42
43


44
45
46
47
48
49
50
..
52
53
54
55
56
57
58


59
60
61
62
63
64
65
66




67
68
69
70
71
72
73
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Data.Common;

namespace SQLite.Designer.Design
{







  [TypeConverter(typeof(ExpandableObjectConverter))]
  [DefaultProperty("Enabled")]
  internal class Unique : IHaveConnection
  {
    private bool _isUnique;
    private ConflictEnum _conflict = ConflictEnum.Abort;
    private Column _column;
................................................................................
    }

    #endregion


    [DefaultValue(false)]
    [DisplayName("Enabled")]


    public bool Enabled
    {
      get { return _isUnique; }
      set
      {
        if (value != _isUnique)
        {
................................................................................
          _column.Table._owner.MakeDirty();
        }
      }
    }

    [DefaultValue(ConflictEnum.Abort)]
    [DisplayName("On Conflict")]


    public ConflictEnum Conflict
    {
      get { return _conflict; }
      set
      {
        if (_conflict != value)
        {
          _conflict = value;




          _column.Table._owner.MakeDirty();
        }
      }
    }

    public override string ToString()
    {
|
|
|
|
|
|



>
>
>
>
>
>
>







 







>
>







 







>
>








>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
..
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
..
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
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer.Design
{
  using System;
  using System.Collections.Generic;
  using System.Text;
  using System.ComponentModel;
  using System.Data;
  using System.Data.Common;

  [TypeConverter(typeof(ExpandableObjectConverter))]
  [DefaultProperty("Enabled")]
  internal class Unique : IHaveConnection
  {
    private bool _isUnique;
    private ConflictEnum _conflict = ConflictEnum.Abort;
    private Column _column;
................................................................................
    }

    #endregion


    [DefaultValue(false)]
    [DisplayName("Enabled")]
    [RefreshProperties(RefreshProperties.All)]
    [Description("When enabled, all values entered into this column must be unique.")]
    public bool Enabled
    {
      get { return _isUnique; }
      set
      {
        if (value != _isUnique)
        {
................................................................................
          _column.Table._owner.MakeDirty();
        }
      }
    }

    [DefaultValue(ConflictEnum.Abort)]
    [DisplayName("On Conflict")]
    [RefreshProperties(RefreshProperties.All)]
    [Description("Specifies what action to take when the unique constraint on the column is violated.")]
    public ConflictEnum Conflict
    {
      get { return _conflict; }
      set
      {
        if (_conflict != value)
        {
          _conflict = value;
          
          if (_conflict != ConflictEnum.Abort && _isUnique == false)
            _isUnique = true;

          _column.Table._owner.MakeDirty();
        }
      }
    }

    public override string ToString()
    {

Changes to SQLite.Designer/Design/View.cs.








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
..
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
...
127
128
129
130
131
132
133





134
135

136








137
138
139
140
141
142
143
...
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214







namespace SQLite.Designer.Design
{
  using System;
  using System.Data.Common;
  using System.ComponentModel.Design;
  using System.ComponentModel;
  using System.Drawing.Design;
  using System.Collections.Generic;
  using System.Data;
  using System.Text;
  using SQLite.Designer.Editors;

  internal class View : ICustomTypeDescriptor, IHaveConnection
  {
    private string _name;
    private string _oldname;
    private string _sql;
    private string _oldsql;
    private ViewDesignerDoc _owner;
    private string _catalog;
    private DbConnection _connection;



    internal View(string viewName, DbConnection connection, ViewDesignerDoc parent)
    {
      _owner = parent;
      _name = viewName;
      _oldname = viewName;
      _catalog = connection.Database;
................................................................................
      if (String.IsNullOrEmpty(viewName) == false)
      {
        using (DataTable tbl = connection.GetSchema("Views", new string[] { Catalog, null, Name }))
        {
          if (tbl.Rows.Count > 0)
          {
            _sql = tbl.Rows[0]["VIEW_DEFINITION"].ToString();



















            _oldsql = _sql;
          }
          else
          {
            _oldname = null;
          }
        }
      }
    }












    public void Committed()
    {
      _oldsql = _sql;
      _oldname = _name;







    }

    public override string ToString()
    {
      return String.Format("[{0}].[{1}]", Catalog, Name);
    }

    [Category("Storage")]
    [RefreshProperties(RefreshProperties.All)]
    [ParenthesizePropertyName(true)]
    public string Name
    {
      get { return _name; }
      set
      {
        if (_name != value)
        {
          _name = value;
          _owner.Name = value;
          _owner.MakeDirty();
        }
      }
    }

    [Category("Storage")]
    [Editor(typeof(CatalogTypeEditor), typeof(UITypeEditor))]
    [DefaultValue("main")]
    [RefreshProperties(RefreshProperties.All)]
    public string Catalog
    {
      get { return _catalog; }
      //set
      //{
      //  string catalogs = "";
      //  using (DataTable table = _connection.GetSchema("Catalogs"))
      //  {
      //    foreach (DataRow row in table.Rows)
      //    {
      //      catalogs += (row[0].ToString() + ",");
      //    }
      //  }

      //  if (catalogs.IndexOf(value + ",", StringComparison.OrdinalIgnoreCase) == -1)
      //    throw new ArgumentOutOfRangeException("Unrecognized catalog!");

      //  _catalog = value;
      //}
    }
    [Category("Storage")]
    public string Database
    {
      get { return _connection.DataSource; }
    }

    [Browsable(false)]
................................................................................
    public string GetSqlText()
    {
      if (String.Compare(_sql, _oldsql, StringComparison.OrdinalIgnoreCase) == 0 && String.Compare(_name, _oldname, StringComparison.OrdinalIgnoreCase) == 0) return null;

      StringBuilder builder = new StringBuilder();

      if (String.IsNullOrEmpty(_oldname) == false)





        builder.AppendFormat("DROP VIEW [{0}].[{1}];\r\n", Catalog, _oldname);


      builder.AppendFormat("CREATE VIEW [{0}].[{1}] AS {2};\r\n", Catalog, Name, SqlText);









      return builder.ToString();
    }

    #region ICustomTypeDescriptor Members

    AttributeCollection ICustomTypeDescriptor.GetAttributes()
................................................................................
    object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
    {
      return this;
    }

    #endregion

    #region IHaveConnection Members

    public DbConnection GetConnection()
    {
      return _connection;
    }

    #endregion
  }
}
>
>
>
>
>
>
>












|








>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|








>
>
>
>
>
>
>
>
>
>
>





>
>
>
>
>
>
>










|












|




|


<
<
<
<
<
<
<
<
<
<
|
<
<

<
<
<







 







>
>
>
>
>

|
>

>
>
>
>
>
>
>
>







 







<
<
|



|
<
|
<
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
..
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
...
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
...
243
244
245
246
247
248
249


250
251
252
253
254

255

/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer.Design
{
  using System;
  using System.Data.Common;
  using System.ComponentModel.Design;
  using System.ComponentModel;
  using System.Drawing.Design;
  using System.Collections.Generic;
  using System.Data;
  using System.Text;
  using SQLite.Designer.Editors;

  internal class View : ViewTableBase, ICustomTypeDescriptor
  {
    private string _name;
    private string _oldname;
    private string _sql;
    private string _oldsql;
    private ViewDesignerDoc _owner;
    private string _catalog;
    private DbConnection _connection;
    List<ViewTrigger> _triggers = new List<ViewTrigger>();
    List<ViewTrigger> _oldtriggers = new List<ViewTrigger>();

    internal View(string viewName, DbConnection connection, ViewDesignerDoc parent)
    {
      _owner = parent;
      _name = viewName;
      _oldname = viewName;
      _catalog = connection.Database;
................................................................................
      if (String.IsNullOrEmpty(viewName) == false)
      {
        using (DataTable tbl = connection.GetSchema("Views", new string[] { Catalog, null, Name }))
        {
          if (tbl.Rows.Count > 0)
          {
            _sql = tbl.Rows[0]["VIEW_DEFINITION"].ToString();

            StringBuilder builder = new StringBuilder();
            builder.Append(_sql);
            builder.AppendLine(";");

            _triggers.Clear();
            _oldtriggers.Clear();

            using (DataTable ttbl = _connection.GetSchema("Triggers", new string[] { Catalog, null, Name }))
            {
              foreach (DataRow row in ttbl.Rows)
              {
                ViewTrigger t = new ViewTrigger(this, row);
                _triggers.Add(t);
                _oldtriggers.Add(((ICloneable)t).Clone() as ViewTrigger);

                builder.AppendFormat("{0};\r\n", t.OriginalSql);
              }
            }
            _oldsql = builder.ToString();
          }
          else
          {
            _oldname = null;
          }
        }
      }
    }

    public override void MakeDirty()
    {
      _owner.MakeDirty();
    }

    [Browsable(false)]
    public override object Triggers
    {
      get { return _triggers; }
    }

    public void Committed()
    {
      _oldsql = _sql;
      _oldname = _name;

      _oldtriggers = _triggers;
      _triggers.Clear();
      foreach (ViewTrigger trig in _oldtriggers)
      {
        _triggers.Add(((ICloneable)trig).Clone() as ViewTrigger);
      }
    }

    public override string ToString()
    {
      return String.Format("[{0}].[{1}]", Catalog, Name);
    }

    [Category("Storage")]
    [RefreshProperties(RefreshProperties.All)]
    [ParenthesizePropertyName(true)]
    public override string Name
    {
      get { return _name; }
      set
      {
        if (_name != value)
        {
          _name = value;
          _owner.Name = value;
          _owner.MakeDirty();
        }
      }
    }
  
    [Category("Storage")]
    [Editor(typeof(CatalogTypeEditor), typeof(UITypeEditor))]
    [DefaultValue("main")]
    [RefreshProperties(RefreshProperties.All)]
    public override string Catalog
    {
      get { return _catalog; }










    }






    [Category("Storage")]
    public string Database
    {
      get { return _connection.DataSource; }
    }

    [Browsable(false)]
................................................................................
    public string GetSqlText()
    {
      if (String.Compare(_sql, _oldsql, StringComparison.OrdinalIgnoreCase) == 0 && String.Compare(_name, _oldname, StringComparison.OrdinalIgnoreCase) == 0) return null;

      StringBuilder builder = new StringBuilder();

      if (String.IsNullOrEmpty(_oldname) == false)
      {
        foreach (ViewTrigger trig in _oldtriggers)
        {
          builder.AppendFormat("DROP TRIGGER [{0}].[{1}];\r\n", Catalog, trig.Name);
        }
        builder.AppendFormat("DROP VIEW [{0}].[{1}];\r\n", Catalog, _oldname);
      }

      builder.AppendFormat("CREATE VIEW [{0}].[{1}] AS {2};\r\n", Catalog, Name, SqlText);

      string sep = "";
      foreach (ViewTrigger trig in _triggers)
      {
        builder.Append(sep);
        trig.WriteSql(builder);
        sep = "\r\n";
      }

      return builder.ToString();
    }

    #region ICustomTypeDescriptor Members

    AttributeCollection ICustomTypeDescriptor.GetAttributes()
................................................................................
    object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
    {
      return this;
    }

    #endregion



    public override DbConnection GetConnection()
    {
      return _connection;
    }
  }

}

Changes to SQLite.Designer/Editors/AutoCompleteColumn.cs.










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
..
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
..
97
98
99
100
101
102
103

104
105
106
107
108
109
110









using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;

namespace SQLite.Designer.Editors
{
  public class DbGridView : DataGridView
  {
    private TableDesignerDoc _owner = null;

    public override void NotifyCurrentCellDirty(bool dirty)
    {
      base.NotifyCurrentCellDirty(dirty);
      SQLite.Designer.Design.Column col = Rows[CurrentCell.RowIndex].Tag as SQLite.Designer.Design.Column;

      if (_owner == null)
      {
        Control ctl = this;

        while (ctl.GetType() != typeof(TableDesignerDoc))
        {
          ctl = ctl.Parent;
          if (ctl == null) break;
        }
        if (ctl != null) _owner = ctl as TableDesignerDoc;
      }

      if (col == null && CurrentRow.IsNewRow == false)
      {
        col = new SQLite.Designer.Design.Column(_owner._table, Rows[CurrentCell.RowIndex]);
        Rows[CurrentCell.RowIndex].Tag = col;
        _owner._table.Columns.Insert(CurrentCell.RowIndex, col);
        base.OnSelectionChanged(new EventArgs());
      }
      if (col != null)
        col.CellValueChanged();

      if (_owner != null)
        _owner.RefreshToolbars();
    }
  }

  public class AutoCompleteColumn : DataGridViewColumn
  {
    public AutoCompleteColumn()
      : base(new AutoCompleteCell())
    {
    }
................................................................................
    public override Type EditType
    {
      get
      {
        return typeof(AutoCompleteEditingControl);
      }
    }

    protected override bool SetValue(int rowIndex, object value)
    {
      return base.SetValue(rowIndex, value);
    }
  }

  public class AutoCompleteEditingControl : DataGridViewComboBoxEditingControl
  {
    private bool inPrepare = false;
    private bool isDeleting = false;

................................................................................
        base.Items.Add("nvarchar(50)");
        base.Items.Add("text");
        base.Items.Add("ntext");
        base.Items.Add("image");
        base.Items.Add("money");
        base.Items.Add("float");
        base.Items.Add("real");

        base.Items.Add("numeric(18,0)");
        base.Items.Add("char(10)");
        base.Items.Add("nchar(10)");
        base.Items.Add("datetime");
        base.Items.Add("guid");
      }
      base.DropDownStyle = ComboBoxStyle.DropDown;
>
>
>
>
>
>
>
>
>
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







<
<
<
<
<







 







>







1
2
3
4
5
6
7
8
9
10
11
12
13






































14
15
16
17
18
19
20
..
25
26
27
28
29
30
31





32
33
34
35
36
37
38
..
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer.Editors
{
  using System;
  using System.Windows.Forms;
  using System.Runtime.InteropServices;
  using System.Drawing;







































  public class AutoCompleteColumn : DataGridViewColumn
  {
    public AutoCompleteColumn()
      : base(new AutoCompleteCell())
    {
    }
................................................................................
    public override Type EditType
    {
      get
      {
        return typeof(AutoCompleteEditingControl);
      }
    }





  }

  public class AutoCompleteEditingControl : DataGridViewComboBoxEditingControl
  {
    private bool inPrepare = false;
    private bool isDeleting = false;

................................................................................
        base.Items.Add("nvarchar(50)");
        base.Items.Add("text");
        base.Items.Add("ntext");
        base.Items.Add("image");
        base.Items.Add("money");
        base.Items.Add("float");
        base.Items.Add("real");
        base.Items.Add("decimal");
        base.Items.Add("numeric(18,0)");
        base.Items.Add("char(10)");
        base.Items.Add("nchar(10)");
        base.Items.Add("datetime");
        base.Items.Add("guid");
      }
      base.DropDownStyle = ComboBoxStyle.DropDown;

Changes to SQLite.Designer/Editors/TableDesignerDoc.Designer.cs.

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
...
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
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.components = new System.ComponentModel.Container();
      System.Windows.Forms.SplitContainer _splitter;
      System.Windows.Forms.SplitContainer splitContainer1;
      System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TableDesignerDoc));
      this._dataGrid = new SQLite.Designer.Editors.DbGridView();
      this.name = new System.Windows.Forms.DataGridViewTextBoxColumn();
      this.type = new SQLite.Designer.Editors.AutoCompleteColumn();
      this.isnull = new System.Windows.Forms.DataGridViewCheckBoxColumn();
      this._sqlText = new System.Windows.Forms.RichTextBox();
      this._propertyGrid = new System.Windows.Forms.PropertyGrid();

      this.autoCompleteColumn1 = new SQLite.Designer.Editors.AutoCompleteColumn();
      this._imageList = new System.Windows.Forms.ImageList(this.components);
      this._timer = new System.Windows.Forms.Timer(this.components);
      this._pg = new System.Windows.Forms.PropertyGrid();
      _splitter = new System.Windows.Forms.SplitContainer();
      splitContainer1 = new System.Windows.Forms.SplitContainer();
      _splitter.Panel1.SuspendLayout();
      _splitter.Panel2.SuspendLayout();
      _splitter.SuspendLayout();
      splitContainer1.Panel1.SuspendLayout();
      splitContainer1.Panel2.SuspendLayout();
      splitContainer1.SuspendLayout();
      ((System.ComponentModel.ISupportInitialize)(this._dataGrid)).BeginInit();
      this.SuspendLayout();
      // 
      // _splitter
      // 
      _splitter.BackColor = System.Drawing.SystemColors.Control;
      _splitter.Dock = System.Windows.Forms.DockStyle.Fill;
      _splitter.Location = new System.Drawing.Point(0, 0);
      _splitter.Name = "_splitter";
      _splitter.Orientation = System.Windows.Forms.Orientation.Horizontal;
      // 
      // _splitter.Panel1
      // 

      _splitter.Panel1.Controls.Add(splitContainer1);

      // 
      // _splitter.Panel2
      // 
      _splitter.Panel2.Controls.Add(this._sqlText);
      _splitter.Size = new System.Drawing.Size(436, 631);
      _splitter.SplitterDistance = 465;
      _splitter.TabIndex = 0;
      // 
      // splitContainer1
      // 
      splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
      splitContainer1.Location = new System.Drawing.Point(0, 0);
      splitContainer1.Name = "splitContainer1";
      splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
      // 
      // splitContainer1.Panel1
      // 
      splitContainer1.Panel1.Controls.Add(this._dataGrid);
      // 
      // splitContainer1.Panel2
      // 
      splitContainer1.Panel2.Controls.Add(this._propertyGrid);
      splitContainer1.Size = new System.Drawing.Size(436, 465);
      splitContainer1.SplitterDistance = 215;
      splitContainer1.TabIndex = 0;
      // 
      // _dataGrid
      // 

      this._dataGrid.AllowUserToResizeRows = false;
      this._dataGrid.BackgroundColor = System.Drawing.SystemColors.Window;
      this._dataGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
      this._dataGrid.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.name,
            this.type,
            this.isnull});
      this._dataGrid.Dock = System.Windows.Forms.DockStyle.Fill;
      this._dataGrid.Location = new System.Drawing.Point(0, 0);
      this._dataGrid.Name = "_dataGrid";
      this._dataGrid.RowHeadersWidth = 42;
      this._dataGrid.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing;
      this._dataGrid.RowTemplate.Height = 23;
      this._dataGrid.Size = new System.Drawing.Size(436, 215);
      this._dataGrid.TabIndex = 2;
      this._dataGrid.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this._dataGrid_CellValueChanged);




      this._dataGrid.UserDeletedRow += new System.Windows.Forms.DataGridViewRowEventHandler(this._dataGrid_UserDeletedRow);

      this._dataGrid.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this._dataGrid_RowsAdded);
      this._dataGrid.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this._dataGrid_CellPainting);
      this._dataGrid.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this._dataGrid_CellClick);
      this._dataGrid.CellEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this._dataGrid_CellEnter);
      this._dataGrid.RowsRemoved += new System.Windows.Forms.DataGridViewRowsRemovedEventHandler(this._dataGrid_RowsRemoved);
      this._dataGrid.RowHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this._dataGrid_RowHeaderMouseClick);
      this._dataGrid.SelectionChanged += new System.EventHandler(this._dataGrid_SelectionChanged);

      // 
      // name
      // 
      this.name.Frozen = true;
      this.name.HeaderText = "Column Name";
      this.name.Name = "name";
      this.name.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
................................................................................
      this.type.Name = "type";
      // 
      // isnull
      // 
      this.isnull.HeaderText = "Allow Nulls";
      this.isnull.Name = "isnull";
      // 
      // _sqlText
      // 
      this._sqlText.Dock = System.Windows.Forms.DockStyle.Fill;
      this._sqlText.Location = new System.Drawing.Point(0, 0);
      this._sqlText.Name = "_sqlText";
      this._sqlText.ReadOnly = true;
      this._sqlText.Size = new System.Drawing.Size(436, 162);
      this._sqlText.TabIndex = 0;
      this._sqlText.Text = "";
      // 
      // _propertyGrid
      // 
      this._propertyGrid.Dock = System.Windows.Forms.DockStyle.Fill;
      this._propertyGrid.Location = new System.Drawing.Point(0, 0);
      this._propertyGrid.Name = "_propertyGrid";
      this._propertyGrid.Size = new System.Drawing.Size(436, 246);
      this._propertyGrid.TabIndex = 0;
      // 











      // autoCompleteColumn1
      // 
      this.autoCompleteColumn1.HeaderText = "Data Type";
      this.autoCompleteColumn1.Name = "autoCompleteColumn1";
      this.autoCompleteColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.True;
      this.autoCompleteColumn1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
      // 
      // _imageList
      // 
      this._imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("_imageList.ImageStream")));
      this._imageList.TransparentColor = System.Drawing.Color.Magenta;
      this._imageList.Images.SetKeyName(0, "PrimaryKey.bmp");
      // 
      // _timer
      // 
      this._timer.Tick += new System.EventHandler(this._timer_Tick);
      // 
      // _pg
      // 
      this._pg.Location = new System.Drawing.Point(0, 0);
      this._pg.Name = "_pg";
      this._pg.PropertySort = System.Windows.Forms.PropertySort.NoSort;
      this._pg.Size = new System.Drawing.Size(130, 130);
      this._pg.TabIndex = 1;
      this._pg.ToolbarVisible = false;
      this._pg.Visible = false;
      // 
      // TableDesignerDoc
      // 
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
      this.BackColor = System.Drawing.SystemColors.Window;
      this.Controls.Add(this._pg);
      this.Controls.Add(_splitter);
      this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
      this.Name = "TableDesignerDoc";
      this.Size = new System.Drawing.Size(436, 631);
      this.VisibleChanged += new System.EventHandler(this.TableDesignerDoc_VisibleChanged);
      _splitter.Panel1.ResumeLayout(false);
      _splitter.Panel2.ResumeLayout(false);
      _splitter.ResumeLayout(false);
      splitContainer1.Panel1.ResumeLayout(false);
      splitContainer1.Panel2.ResumeLayout(false);
      splitContainer1.ResumeLayout(false);
      ((System.ComponentModel.ISupportInitialize)(this._dataGrid)).EndInit();
      this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.PropertyGrid _propertyGrid;
    private AutoCompleteColumn autoCompleteColumn1;
    private System.Windows.Forms.ImageList _imageList;
    private DbGridView _dataGrid;
    private System.Windows.Forms.DataGridViewTextBoxColumn name;
    private AutoCompleteColumn type;
    private System.Windows.Forms.DataGridViewCheckBoxColumn isnull;
    private System.Windows.Forms.RichTextBox _sqlText;
    private System.Windows.Forms.Timer _timer;
    private System.Windows.Forms.PropertyGrid _pg;

  }
}







<

|



<

>


<


<



<
<
<













>
|
>



|

|


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


>













|


>
>
>
>

>
|



<


>







 







<
<
<
<
<
<
<
<
<
<





|


>
>
>
>
>
>
>
>
>
>
>













<
<
<
<


|












<

<


<



<
<
<










|




<




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
...
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
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.components = new System.ComponentModel.Container();
      System.Windows.Forms.SplitContainer _splitter;

      System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TableDesignerDoc));
      this._dataGrid = new System.Windows.Forms.DataGridView();
      this.name = new System.Windows.Forms.DataGridViewTextBoxColumn();
      this.type = new SQLite.Designer.Editors.AutoCompleteColumn();
      this.isnull = new System.Windows.Forms.DataGridViewCheckBoxColumn();

      this._propertyGrid = new System.Windows.Forms.PropertyGrid();
      this._sqlText = new System.Windows.Forms.RichTextBox();
      this.autoCompleteColumn1 = new SQLite.Designer.Editors.AutoCompleteColumn();
      this._imageList = new System.Windows.Forms.ImageList(this.components);

      this._pg = new System.Windows.Forms.PropertyGrid();
      _splitter = new System.Windows.Forms.SplitContainer();

      _splitter.Panel1.SuspendLayout();
      _splitter.Panel2.SuspendLayout();
      _splitter.SuspendLayout();



      ((System.ComponentModel.ISupportInitialize)(this._dataGrid)).BeginInit();
      this.SuspendLayout();
      // 
      // _splitter
      // 
      _splitter.BackColor = System.Drawing.SystemColors.Control;
      _splitter.Dock = System.Windows.Forms.DockStyle.Fill;
      _splitter.Location = new System.Drawing.Point(0, 0);
      _splitter.Name = "_splitter";
      _splitter.Orientation = System.Windows.Forms.Orientation.Horizontal;
      // 
      // _splitter.Panel1
      // 
      _splitter.Panel1.Controls.Add(this._dataGrid);
      _splitter.Panel1.Controls.Add(this._pg);
      _splitter.Panel1.Controls.Add(this._sqlText);
      // 
      // _splitter.Panel2
      // 
      _splitter.Panel2.Controls.Add(this._propertyGrid);
      _splitter.Size = new System.Drawing.Size(436, 631);
      _splitter.SplitterDistance = 383;
      _splitter.TabIndex = 0;
      // 


















      // _dataGrid
      // 
      this._dataGrid.AllowDrop = true;
      this._dataGrid.AllowUserToResizeRows = false;
      this._dataGrid.BackgroundColor = System.Drawing.SystemColors.Window;
      this._dataGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
      this._dataGrid.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.name,
            this.type,
            this.isnull});
      this._dataGrid.Dock = System.Windows.Forms.DockStyle.Fill;
      this._dataGrid.Location = new System.Drawing.Point(0, 0);
      this._dataGrid.Name = "_dataGrid";
      this._dataGrid.RowHeadersWidth = 42;
      this._dataGrid.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing;
      this._dataGrid.RowTemplate.Height = 23;
      this._dataGrid.Size = new System.Drawing.Size(436, 383);
      this._dataGrid.TabIndex = 2;
      this._dataGrid.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this._dataGrid_CellValueChanged);
      this._dataGrid.MouseDown += new System.Windows.Forms.MouseEventHandler(this._dataGrid_MouseDown);
      this._dataGrid.UserDeletingRow += new System.Windows.Forms.DataGridViewRowCancelEventHandler(this._dataGrid_UserDeletingRow);
      this._dataGrid.MouseMove += new System.Windows.Forms.MouseEventHandler(this._dataGrid_MouseMove);
      this._dataGrid.CellValidated += new System.Windows.Forms.DataGridViewCellEventHandler(this._dataGrid_CellValidated);
      this._dataGrid.UserDeletedRow += new System.Windows.Forms.DataGridViewRowEventHandler(this._dataGrid_UserDeletedRow);
      this._dataGrid.DragOver += new System.Windows.Forms.DragEventHandler(this._dataGrid_DragOver);
      this._dataGrid.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this._dataGrid_CellValidated);
      this._dataGrid.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this._dataGrid_CellPainting);
      this._dataGrid.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this._dataGrid_CellClick);
      this._dataGrid.CellEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this._dataGrid_CellEnter);

      this._dataGrid.RowHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this._dataGrid_RowHeaderMouseClick);
      this._dataGrid.SelectionChanged += new System.EventHandler(this._dataGrid_SelectionChanged);
      this._dataGrid.DragDrop += new System.Windows.Forms.DragEventHandler(this._dataGrid_DragDrop);
      // 
      // name
      // 
      this.name.Frozen = true;
      this.name.HeaderText = "Column Name";
      this.name.Name = "name";
      this.name.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
................................................................................
      this.type.Name = "type";
      // 
      // isnull
      // 
      this.isnull.HeaderText = "Allow Nulls";
      this.isnull.Name = "isnull";
      // 










      // _propertyGrid
      // 
      this._propertyGrid.Dock = System.Windows.Forms.DockStyle.Fill;
      this._propertyGrid.Location = new System.Drawing.Point(0, 0);
      this._propertyGrid.Name = "_propertyGrid";
      this._propertyGrid.Size = new System.Drawing.Size(436, 244);
      this._propertyGrid.TabIndex = 0;
      // 
      // _sqlText
      // 
      this._sqlText.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
      this._sqlText.Location = new System.Drawing.Point(3, 3);
      this._sqlText.Name = "_sqlText";
      this._sqlText.ReadOnly = true;
      this._sqlText.Size = new System.Drawing.Size(165, 162);
      this._sqlText.TabIndex = 0;
      this._sqlText.Text = "";
      this._sqlText.Visible = false;
      // 
      // autoCompleteColumn1
      // 
      this.autoCompleteColumn1.HeaderText = "Data Type";
      this.autoCompleteColumn1.Name = "autoCompleteColumn1";
      this.autoCompleteColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.True;
      this.autoCompleteColumn1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
      // 
      // _imageList
      // 
      this._imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("_imageList.ImageStream")));
      this._imageList.TransparentColor = System.Drawing.Color.Magenta;
      this._imageList.Images.SetKeyName(0, "PrimaryKey.bmp");
      // 




      // _pg
      // 
      this._pg.Location = new System.Drawing.Point(3, 171);
      this._pg.Name = "_pg";
      this._pg.PropertySort = System.Windows.Forms.PropertySort.NoSort;
      this._pg.Size = new System.Drawing.Size(130, 130);
      this._pg.TabIndex = 1;
      this._pg.ToolbarVisible = false;
      this._pg.Visible = false;
      // 
      // TableDesignerDoc
      // 
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
      this.BackColor = System.Drawing.SystemColors.Window;

      this.Controls.Add(_splitter);

      this.Name = "TableDesignerDoc";
      this.Size = new System.Drawing.Size(436, 631);

      _splitter.Panel1.ResumeLayout(false);
      _splitter.Panel2.ResumeLayout(false);
      _splitter.ResumeLayout(false);



      ((System.ComponentModel.ISupportInitialize)(this._dataGrid)).EndInit();
      this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.PropertyGrid _propertyGrid;
    private AutoCompleteColumn autoCompleteColumn1;
    private System.Windows.Forms.ImageList _imageList;
    private System.Windows.Forms.DataGridView _dataGrid;
    private System.Windows.Forms.DataGridViewTextBoxColumn name;
    private AutoCompleteColumn type;
    private System.Windows.Forms.DataGridViewCheckBoxColumn isnull;
    private System.Windows.Forms.RichTextBox _sqlText;

    private System.Windows.Forms.PropertyGrid _pg;

  }
}

Changes to SQLite.Designer/Editors/TableDesignerDoc.cs.








1
2
3
4
5
6
7
..
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
...
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
...
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
...
259
260
261
262
263
264
265























266
267
268
269
270
271
272
273
274
275
276
277
278
279
...
281
282
283
284
285
286
287






288
289
290
291
292
293
294
...
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
...
394
395
396
397
398
399
400

401
402
403
404








405
406
407
408
409
410
411
...
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
...
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
...
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
...
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924







namespace SQLite.Designer.Editors
{
  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Data.Common;
................................................................................
    private static Dictionary<int, string> _editingTables = new Dictionary<int, string>();
    
    internal DataConnection _connection;
    internal Microsoft.VisualStudio.Data.ServiceProvider _serviceProvider;
    internal Table _table;
    internal bool _dirty;
    internal bool _init = false;



    private bool _warned = false;

    public TableDesignerDoc(DataConnection cnn, string tableName)

    {

      _connection = cnn;

      _init = true;

      InitializeComponent();

      StringBuilder tables = new StringBuilder();

      using (DataReader reader = cnn.Command.Execute("SELECT * FROM sqlite_master", 1, null, 30))
      {
        while (reader.Read())
        {
          tables.Append(reader.GetItem(2).ToString());
          tables.Append(",");
        }
      }
................................................................................
        shell.UpdateDocDataIsDirtyFeedback(docCookie, (_dirty == true) ? 1 : 0);
      }

      // Unlock the document.
      // Note that we have to unlock the document even if the previous call failed.
      runningDocTable.UnlockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, docCookie);


      // Check ff the call to NotifyDocChanged failed.
      //ErrorHandler.ThrowOnFailure(hr);
    }

    #region IVsPersistDocData Members

    int IVsPersistDocData.Close()
................................................................................
    }

    public int RenameDocData(uint grfAttribs, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
    {
      return VSConstants.E_NOTIMPL;
    }

    public int SaveDocData(VSSAVEFLAGS dwSave, out string pbstrMkDocumentNew, out int pfSaveCanceled)
    {
      pbstrMkDocumentNew = _table.Name;
      pfSaveCanceled = 0;

      if (String.IsNullOrEmpty(_table.OriginalSql) == true)
      {
        using (TableNameDialog dlg = new TableNameDialog("Table", _table.Name))
        {
          if (dlg.ShowDialog(this) == DialogResult.Cancel)
          {
            pfSaveCanceled = 1;
            return VSConstants.S_OK;
          }
          _table.Name = dlg.TableName;
        }
      }

      _init = true;
      for (int n = 0; n < _table.Columns.Count; n++)
      {
        Column c = _table.Columns[n];
        if (String.IsNullOrEmpty(c.ColumnName) == true)
        {


          _dataGrid.Rows.Remove(c.Parent);





          _table.Columns.Remove(c);
          n--;
          continue;
        }
      }

      for (int n = 0; n < _dataGrid.Rows.Count; n++)
................................................................................
            if (n == _dataGrid.Rows.Count - 1) break;
          }
          n--;
        }
      }
      _init = false;
























      using (DbTransaction trans = _table.GetConnection().BeginTransaction())
      {
        try
        {
          using (DbCommand cmd = _table.GetConnection().CreateCommand())
          {
            cmd.CommandText = _table.GetSql();
            cmd.ExecuteNonQuery();
          }
          trans.Commit();
        }
        catch (Exception)
        {
          trans.Rollback();
................................................................................
        }
      }

      _dirty = false;
      _table.Committed();
      NotifyChanges();
      _sqlText.Text = _table.OriginalSql;







      return VSConstants.S_OK;
    }

    public int SetUntitledDocPath(string pszDocDataPath)
    {
      return ((IPersistFileFormat)this).InitNew(0);
................................................................................

    #endregion

    #region IVsWindowPane Members

    public int ClosePane()
    {
      if (_serviceProvider != null)
      {
        EnvDTE.DTE dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE));

        //Show toolbar
        if (dte != null)
        {
          Microsoft.VisualStudio.CommandBars.CommandBars commandBars = (Microsoft.VisualStudio.CommandBars.CommandBars)dte.CommandBars;
          Microsoft.VisualStudio.CommandBars.CommandBar bar = commandBars["Table Designer"];
          bar.Visible = false;
        }
      }
      this.Dispose(true);
      return VSConstants.S_OK;
    }

    public int CreatePaneWindow(IntPtr hwndParent, int x, int y, int cx, int cy, out IntPtr hwnd)
    {
      Win32Methods.SetParent(Handle, hwndParent);
................................................................................
      return newVal;
    }

    #region IOleCommandTarget Members

    public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
    {

      if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
      {
        switch ((VSConstants.VSStd97CmdID)nCmdID)
        {








          case VSConstants.VSStd97CmdID.PrimaryKey:
            bool newVal = IsPkSelected();

            if (newVal == false)
            {
              _table.PrimaryKey.Columns.Clear();
              foreach (Column c in _propertyGrid.SelectedObjects)
................................................................................
                }
              }
            }

            _dataGrid_SelectionChanged(this, EventArgs.Empty);
            _dataGrid.Invalidate();
            MakeDirty();
            return VSConstants.S_OK;
        }







      }











































































      else if (pguidCmdGroup == SQLiteCommandHandler.guidDavinci)
      {
        switch ((VSConstants.VSStd97CmdID)nCmdID)
        {
          case VSConstants.VSStd97CmdID.ManageIndexes:
            IndexHolder holder = new IndexHolder(_table.Indexes, _table.ForeignKeys);

            _pg.SelectedObject = holder;
            _pg.SelectedGridItem = _pg.SelectedGridItem.Parent.GridItems[0];
            IndexEditor ed = new IndexEditor(_table);
            ed.EditValue((ITypeDescriptorContext)_pg.SelectedGridItem, (System.IServiceProvider)_pg.SelectedGridItem, _pg.SelectedGridItem.Value);
            return VSConstants.S_OK;
          case VSConstants.VSStd97CmdID.ManageRelationships:
            holder = new IndexHolder(_table.Indexes, _table.ForeignKeys);
            _pg.SelectedObject = holder;
            _pg.SelectedGridItem = _pg.SelectedGridItem.Parent.GridItems[1];
            ForeignKeyEditor fed = new ForeignKeyEditor(_table);
            fed.EditValue((ITypeDescriptorContext)_pg.SelectedGridItem, (System.IServiceProvider)_pg.SelectedGridItem, _pg.SelectedGridItem.Value);
            return VSConstants.S_OK;









          case VSConstants.VSStd97CmdID.AlignRight: // Insert Column

            _dataGrid.Rows.Insert(_dataGrid.SelectedRows[0].Index, 1);
            return VSConstants.S_OK;
          case VSConstants.VSStd97CmdID.AlignToGrid: // Delete Column


            while (_dataGrid.SelectedRows.Count > 0)
            {
              try
              {
                DataGridViewRow row = _dataGrid.SelectedRows[0];
                Column c = row.Tag as Column;
                row.Selected = false;
                if (c != null)

                  _table.Columns.Remove(c);


                _dataGrid.Rows.Remove(row);
              }
              catch
              {
              }
            }














            return VSConstants.S_OK;
        }
      }

      return (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
    }




















    public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
    {
      if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
      {
        switch ((VSConstants.VSStd97CmdID)prgCmds[0].cmdID)
        {
          case VSConstants.VSStd97CmdID.PrimaryKey:
            prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
            if (IsPkSelected() == true)
              prgCmds[0].cmdf |= (uint)(OLECMDF.OLECMDF_LATCHED);

            break;
          //case VSConstants.VSStd97CmdID.GenerateChangeScript:


          //  prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
          //  break;
























          default:
            return (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
        }
        return VSConstants.S_OK;
      }











      if (pguidCmdGroup == SQLiteCommandHandler.guidDavinci)
      {
        switch (prgCmds[0].cmdID)
        {
          case (uint)VSConstants.VSStd97CmdID.ManageRelationships:
          case (uint)VSConstants.VSStd97CmdID.ManageIndexes:
          //case (uint)VSConstants.VSStd97CmdID.ManageConstraints:
          //case 10: // Table View -> Custom
          //case 14: // Table View -> Modify Custom
          //case 33: // Database Diagram -> Add Table
          //case 1: // Database Diagram -> Add Related Tables
          //case 12: // Database Diagram -> Delete From Database
          //case 51: // Database Diagram -> Remove From Diagram
          //case 13: // Database Diagram -> Autosize Selected Tables
................................................................................
    }

    int IVsWindowFrameNotify.OnMove()
    {
      return VSConstants.S_OK;
    }

    private void _timer_Tick(object sender, EventArgs e)
    {
      _timer.Enabled = false;
      if (_serviceProvider != null)
      {
        EnvDTE.DTE dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE));

        //Show toolbar
        if (dte != null)
        {
          Microsoft.VisualStudio.CommandBars.CommandBars commandBars = (Microsoft.VisualStudio.CommandBars.CommandBars)dte.CommandBars;
          Microsoft.VisualStudio.CommandBars.CommandBar bar = commandBars["Table Designer"];
          bar.Visible = true;
        }
      }

      if (_warned == false)
      {
        _warned = true;
        if (_table.HasCheck == true)
          MessageBox.Show(this, "This table has CHECK constraints that could not be parsed.  Before making any changes to this table, make sure you note the constraints in the SQL window first", "Parser Error");
      }
    }

    int IVsWindowFrameNotify.OnShow(int fShow)
    {
      switch ((__FRAMESHOW)fShow)
      {
        case __FRAMESHOW.FRAMESHOW_WinShown:
          SetPropertyWindow();
          _timer.Enabled = true;
          break;
        case __FRAMESHOW.FRAMESHOW_WinHidden:



          break;
      }
      return VSConstants.S_OK;
    }

    int IVsWindowFrameNotify.OnSize()
    {
................................................................................
      return VSConstants.S_OK;
    }

    #endregion

    private void _dataGrid_CellEnter(object sender, DataGridViewCellEventArgs e)
    {


      if (e.ColumnIndex > -1)
      {
        _dataGrid.BeginEdit(true);
        _dataGrid_SelectionChanged(sender, e);




      }
    }

    private void _dataGrid_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
      _dataGrid.EndEdit();
      if (e.Button == MouseButtons.Right)
................................................................................
      if (ispk == true)
      {
        e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
        _imageList.Draw(e.Graphics, e.CellBounds.Left, e.CellBounds.Top + ((e.CellBounds.Bottom - e.CellBounds.Top) - _imageList.ImageSize.Height) / 2, 0);
        e.Handled = true;
      }
    }























    private void _dataGrid_SelectionChanged(object sender, EventArgs e)
    {
      if (_init == true) return;
      List<object> items = new List<object>();

      for (int n = 0; n < _dataGrid.Rows.Count; n++)
      {
        if (_dataGrid.Rows[n].Selected || (_dataGrid.CurrentCell.RowIndex == n && _dataGrid.IsCurrentCellInEditMode == true))
        {
          if (_dataGrid.Rows[n].Tag != null)
            items.Add(_dataGrid.Rows[n].Tag);
        }
      }

      object[] objs = new object[items.Count];
      items.CopyTo(objs);


      _propertyGrid.SelectedObjects = objs;

      IVsUIShell shell = _serviceProvider.GetService(typeof(IVsUIShell)) as IVsUIShell;
      if (shell != null)
      {
        shell.UpdateCommandUI(0);
      }
    }

    private void _dataGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
      if (_init == true) return;
      if (e.RowIndex > -1)
      {
        MakeDirty();
        _propertyGrid.SelectedObjects = _propertyGrid.SelectedObjects;
      }
    }

    private void _dataGrid_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
    {
      if (_init == true) return;




      _dataGrid_SelectionChanged(sender, e);
    }










    private void _dataGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    {
      if (_init == true) return;
      MakeDirty();
    }


    private void _dataGrid_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
    {
      if (_init == true) return;
































      MakeDirty();

    }

    private void TableDesignerDoc_VisibleChanged(object sender, EventArgs e)
    {





    }



  }




































































  internal class IndexHolder
  {
    private List<Index> _indexes;
    private List<ForeignKey> _fkeys;



    internal IndexHolder(List<Index> idx, List<ForeignKey> fk)

    {
      _indexes = idx;
      _fkeys = fk;


    }

    public List<Index> Indexes
    {
      get { return _indexes; }
    }

    public List<ForeignKey> ForeignKeys
    {
      get { return _fkeys; }
    }










  }

  public class DesignerDocBase : UserControl
  {
    public virtual string CanonicalName
    {
      get
................................................................................
          pvar = 0;
          break;
        case __VSHPROPID.VSHPROPID_IconHandle:
          pvar = null;
          return VSConstants.S_OK;
      }

      //switch ((__VSHPROPID2)propid)
      //{
      //  case __VSHPROPID2.VSHPROPID_StatusBarClientText:
      //    pvar = "SQLite Table Editor";
      //    break;
      //}

      if (pvar == null)
        return _owner.GetProperty(itemid, propid, out pvar);
      else
        return VSConstants.S_OK;
    }

    int IVsUIHierarchy.GetSite(out Microsoft.VisualStudio.OLE.Interop.IServiceProvider ppSP)
>
>
>
>
>
>
>







 







<
>
>
|

<
>

>
|
>






|







 







<







 







|

|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






>
>
|
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






|







 







>
>
>
>
>
>







 







<
<
<
<
<
<
<
<
<
<
<
<







 







>




>
>
>
>
>
>
>
>







 








|
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





<
>






|





>
>
>
>
>
>
>
>
>

>



>
>








>

>
|






>
>
>
>
>
>
>
>
>
>
>
>
>
>






>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>













|
>
>
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





>
>
>
>
>
>
>
>
>
>







|







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<





|
|
|
|
>
>
>







 







>
>
|
|
|
|
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|

|
|
|
<
<
<
<
<
<
<
<
>



|
<
<
<
<







<







>
>
>
>


>
>
>
>
>
>
>
>
>



<
<
|
|
>


<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
|
|
<
|
>
>
>
>
>
|
>
>
>
|
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|



>
>

<
>

|
|
>
>











>
>
>
>
>
>
>
>
>
>







 







<
<
<
<
<
<
<







1
2
3
4
5
6
7
8
9
10
11
12
13
14
..
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
...
172
173
174
175
176
177
178

179
180
181
182
183
184
185
...
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
...
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
...
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
...
326
327
328
329
330
331
332












333
334
335
336
337
338
339
...
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
...
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
...
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
...
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
....
1223
1224
1225
1226
1227
1228
1229







1230
1231
1232
1233
1234
1235
1236
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer.Editors
{
  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Data.Common;
................................................................................
    private static Dictionary<int, string> _editingTables = new Dictionary<int, string>();
    
    internal DataConnection _connection;
    internal Microsoft.VisualStudio.Data.ServiceProvider _serviceProvider;
    internal Table _table;
    internal bool _dirty;
    internal bool _init = false;

    internal DataViewHierarchyAccessor _accessor;
    internal int _itemId;
    static private bool _warned = false;


    public TableDesignerDoc(int itemId, DataViewHierarchyAccessor accessor, string tableName)
    {
      _accessor = accessor;
      _connection = accessor.Connection;
      _itemId = itemId;
      _init = true;

      InitializeComponent();

      StringBuilder tables = new StringBuilder();

      using (DataReader reader = _connection.Command.Execute("SELECT * FROM sqlite_master", 1, null, 30))
      {
        while (reader.Read())
        {
          tables.Append(reader.GetItem(2).ToString());
          tables.Append(",");
        }
      }
................................................................................
        shell.UpdateDocDataIsDirtyFeedback(docCookie, (_dirty == true) ? 1 : 0);
      }

      // Unlock the document.
      // Note that we have to unlock the document even if the previous call failed.
      runningDocTable.UnlockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, docCookie);


      // Check ff the call to NotifyDocChanged failed.
      //ErrorHandler.ThrowOnFailure(hr);
    }

    #region IVsPersistDocData Members

    int IVsPersistDocData.Close()
................................................................................
    }

    public int RenameDocData(uint grfAttribs, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
    {
      return VSConstants.E_NOTIMPL;
    }

    private string GetChangeScript()
    {
      _dataGrid.EndEdit();















      _init = true;
      for (int n = 0; n < _table.Columns.Count; n++)
      {
        Column c = _table.Columns[n];
        if (String.IsNullOrEmpty(c.ColumnName) == true)
        {
          try
          {
            _dataGrid.Rows.Remove(c.Parent);
          }
          catch
          {
            c.Parent.Tag = null;
          }
          _table.Columns.Remove(c);
          n--;
          continue;
        }
      }

      for (int n = 0; n < _dataGrid.Rows.Count; n++)
................................................................................
            if (n == _dataGrid.Rows.Count - 1) break;
          }
          n--;
        }
      }
      _init = false;

      return _table.GetSql();
    }

    public int SaveDocData(VSSAVEFLAGS dwSave, out string pbstrMkDocumentNew, out int pfSaveCanceled)
    {
      pbstrMkDocumentNew = _table.Name;
      pfSaveCanceled = 0;

      if (String.IsNullOrEmpty(_table.OriginalSql) == true)
      {
        using (TableNameDialog dlg = new TableNameDialog("Table", _table.Name))
        {
          if (dlg.ShowDialog(this) == DialogResult.Cancel)
          {
            pfSaveCanceled = 1;
            return VSConstants.S_OK;
          }
          _table.Name = dlg.TableName;
        }
      }

      string sql = GetChangeScript();

      using (DbTransaction trans = _table.GetConnection().BeginTransaction())
      {
        try
        {
          using (DbCommand cmd = _table.GetConnection().CreateCommand())
          {
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();
          }
          trans.Commit();
        }
        catch (Exception)
        {
          trans.Rollback();
................................................................................
        }
      }

      _dirty = false;
      _table.Committed();
      NotifyChanges();
      _sqlText.Text = _table.OriginalSql;

      SQLiteCommandHandler.Refresh(_accessor, _itemId);

      _dataGrid_SelectionChanged(this, EventArgs.Empty);

      RefreshToolbars();

      return VSConstants.S_OK;
    }

    public int SetUntitledDocPath(string pszDocDataPath)
    {
      return ((IPersistFileFormat)this).InitNew(0);
................................................................................

    #endregion

    #region IVsWindowPane Members

    public int ClosePane()
    {












      this.Dispose(true);
      return VSConstants.S_OK;
    }

    public int CreatePaneWindow(IntPtr hwndParent, int x, int y, int cx, int cy, out IntPtr hwnd)
    {
      Win32Methods.SetParent(Handle, hwndParent);
................................................................................
      return newVal;
    }

    #region IOleCommandTarget Members

    public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
    {
      System.Diagnostics.Debug.WriteLine(String.Format("{0} {1}", pguidCmdGroup, nCmdID));
      if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
      {
        switch ((VSConstants.VSStd97CmdID)nCmdID)
        {
          case VSConstants.VSStd97CmdID.GenerateChangeScript:
            {
              using (ChangeScriptDialog dlg = new ChangeScriptDialog(_table.Name, GetChangeScript()))
              {
                dlg.ShowDialog(this);
              }
            }
            return VSConstants.S_OK;
          case VSConstants.VSStd97CmdID.PrimaryKey:
            bool newVal = IsPkSelected();

            if (newVal == false)
            {
              _table.PrimaryKey.Columns.Clear();
              foreach (Column c in _propertyGrid.SelectedObjects)
................................................................................
                }
              }
            }

            _dataGrid_SelectionChanged(this, EventArgs.Empty);
            _dataGrid.Invalidate();
            MakeDirty();
            return VSConstants.S_OK;

          case VSConstants.VSStd97CmdID.Cut:
            _clipRows = SelectedRows;
            foreach (DataGridViewRow row in _clipRows)
            {
              _dataGrid.Rows.Remove(row);
              _table.Columns.Remove(row.Tag as Column);
              MakeDirty();
            }
            Clipboard.SetData("SQLiteTableDesigner", Caption);
            RefreshToolbars();
            return VSConstants.S_OK;

          case VSConstants.VSStd97CmdID.Copy:
            _clipRows = SelectedRows;
            Clipboard.SetData("SQLiteTableDesigner", Caption);
            RefreshToolbars();
            return VSConstants.S_OK;

          case VSConstants.VSStd97CmdID.Paste:
            DataGridViewRow[] arr = GetClipboardRows();
            int rowIndex = _dataGrid.CurrentRow.Index;
            _dataGrid.EndEdit();

            for (int n = arr.Length - 1; n > -1; n--)
            {
              DataGridViewRow row = arr[n];
              Column c = row.Tag as Column;
              bool hasCol = false;
              foreach (Column oc in _table.Columns)
              {
                if (String.Compare(c.ColumnName, oc.ColumnName, StringComparison.OrdinalIgnoreCase) == 0)
                {
                  hasCol = true;
                  break;
                }
              }
              _dataGrid.Rows.Insert(rowIndex, 1);
              DataGridViewRow newrow = _dataGrid.Rows[rowIndex];

              if (hasCol == true)
              {
                Column oc = c;
                c = new Column(_table, newrow);
                int num = 1;
                while (String.IsNullOrEmpty(c.ColumnName) == true)
                {
                  bool found = false;
                  string proposed = String.Format("{0}{1}", oc.ColumnName, num);
                  foreach (Column cc in _table.Columns)
                  {
                    if (String.Compare(cc.ColumnName, proposed, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                      found = true;
                      break;
                    }
                  }
                  if (found == true)
                  {
                    num++;
                  }
                  else
                    c.ColumnName = proposed;
                }
                c.AllowNulls = oc.AllowNulls;
                c.Collate = oc.Collate;
                c.DataType = oc.DataType;
                c.DefaultValue = oc.DefaultValue;
                c.Unique.Enabled = oc.Unique.Enabled;
                c.Unique.Conflict = oc.Unique.Conflict;
              }

              c.Parent = newrow;
              newrow.Tag = c;
              newrow.SetValues(c.ColumnName, c.DataType, c.AllowNulls);
              _table.Columns.Insert(rowIndex, c);
            }
            
            MakeDirty();
            _dataGrid.Invalidate();

            return VSConstants.S_OK;
        }
      }
      else if (pguidCmdGroup == SQLiteCommandHandler.guidDavinci)
      {
        switch ((VSConstants.VSStd97CmdID)nCmdID)
        {
          case VSConstants.VSStd97CmdID.ManageIndexes:

            EditorHolder holder = new EditorHolder(_table);
            _pg.SelectedObject = holder;
            _pg.SelectedGridItem = _pg.SelectedGridItem.Parent.GridItems[0];
            IndexEditor ed = new IndexEditor(_table);
            ed.EditValue((ITypeDescriptorContext)_pg.SelectedGridItem, (System.IServiceProvider)_pg.SelectedGridItem, _pg.SelectedGridItem.Value);
            return VSConstants.S_OK;
          case VSConstants.VSStd97CmdID.ManageRelationships:
            holder = new EditorHolder(_table);
            _pg.SelectedObject = holder;
            _pg.SelectedGridItem = _pg.SelectedGridItem.Parent.GridItems[1];
            ForeignKeyEditor fed = new ForeignKeyEditor(_table);
            fed.EditValue((ITypeDescriptorContext)_pg.SelectedGridItem, (System.IServiceProvider)_pg.SelectedGridItem, _pg.SelectedGridItem.Value);
            return VSConstants.S_OK;
          
          case VSConstants.VSStd97CmdID.ManageConstraints:
            holder = new EditorHolder(_table);
            _pg.SelectedObject = holder;
            _pg.SelectedGridItem = _pg.SelectedGridItem.Parent.GridItems[2];
            CheckEditor ced = new CheckEditor(_table);
            ced.EditValue((ITypeDescriptorContext)_pg.SelectedGridItem, (System.IServiceProvider)_pg.SelectedGridItem, _pg.SelectedGridItem.Value);
            return VSConstants.S_OK;

          case VSConstants.VSStd97CmdID.AlignRight: // Insert Column
            _dataGrid.EndEdit();
            _dataGrid.Rows.Insert(_dataGrid.SelectedRows[0].Index, 1);
            return VSConstants.S_OK;
          case VSConstants.VSStd97CmdID.AlignToGrid: // Delete Column
            _dataGrid.EndEdit();
            int deleted = 0;
            while (_dataGrid.SelectedRows.Count > 0)
            {
              try
              {
                DataGridViewRow row = _dataGrid.SelectedRows[0];
                Column c = row.Tag as Column;
                row.Selected = false;
                if (c != null)
                {
                  _table.Columns.Remove(c);
                  deleted++;
                }
                _dataGrid.Rows.Remove(row);
              }
              catch
              {
              }
            }
            if (deleted > 0) MakeDirty();
            return VSConstants.S_OK;
        }
      }
      else if (pguidCmdGroup == SQLiteCommandHandler.guidSQLiteCmdSet)
      {
        switch ((cmdid)nCmdID)
        {
          case cmdid.Triggers:
            EditorHolder holder = new EditorHolder(_table);
            _pg.SelectedObject = holder;
            _pg.SelectedGridItem = _pg.SelectedGridItem.Parent.GridItems[3];
            TriggerEditor ted = new TriggerEditor(_table);
            ted.EditValue((ITypeDescriptorContext)_pg.SelectedGridItem, (System.IServiceProvider)_pg.SelectedGridItem, _pg.SelectedGridItem.Value);
            return VSConstants.S_OK;
        }
      }

      return (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
    }

    private DataGridViewRow[] _clipRows;

    private DataGridViewRow[] GetClipboardRows()
    {
      if (Clipboard.ContainsData("SQLiteTableDesigner") && Clipboard.GetData("SQLiteTableDesigner").ToString() == Caption)
      {
        DataGridViewRow[] arr = _clipRows;
        if (arr != null)
        {
          for (int n = 0; n < arr.Length; n++)
          {
            Column c = arr[n].Tag as Column;
            if (c != null && c.Table == _table) return arr;
          }
        }
      }
      return null;
    }

    public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
    {
      if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
      {
        switch ((VSConstants.VSStd97CmdID)prgCmds[0].cmdID)
        {
          case VSConstants.VSStd97CmdID.PrimaryKey:
            prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
            if (IsPkSelected() == true)
              prgCmds[0].cmdf |= (uint)(OLECMDF.OLECMDF_LATCHED);

            break;
          case VSConstants.VSStd97CmdID.GenerateChangeScript:
            if (_dirty == true)
            {
              prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
              break;
            }
            return (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
          case VSConstants.VSStd97CmdID.Cut:
            if (SelectedRows.Length > 0)
            {
              prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
              break;
            }
            return (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
          case VSConstants.VSStd97CmdID.Copy:
            if (SelectedRows.Length > 0)
            {
              prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
              break;
            }
            return (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
          case VSConstants.VSStd97CmdID.Paste:
            DataGridViewRow[] rows = GetClipboardRows();
            if (rows != null)
            {
              prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
              break;
            }
            return (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
          default:
            return (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
        }
        return VSConstants.S_OK;
      }

      if (pguidCmdGroup == SQLiteCommandHandler.guidSQLiteCmdSet)
      {
        switch (prgCmds[0].cmdID)
        {
          case (uint)cmdid.Triggers:
            prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
            return VSConstants.S_OK;
        }
      }

      if (pguidCmdGroup == SQLiteCommandHandler.guidDavinci)
      {
        switch (prgCmds[0].cmdID)
        {
          case (uint)VSConstants.VSStd97CmdID.ManageRelationships:
          case (uint)VSConstants.VSStd97CmdID.ManageIndexes:
          case (uint)VSConstants.VSStd97CmdID.ManageConstraints:
          //case 10: // Table View -> Custom
          //case 14: // Table View -> Modify Custom
          //case 33: // Database Diagram -> Add Table
          //case 1: // Database Diagram -> Add Related Tables
          //case 12: // Database Diagram -> Delete From Database
          //case 51: // Database Diagram -> Remove From Diagram
          //case 13: // Database Diagram -> Autosize Selected Tables
................................................................................
    }

    int IVsWindowFrameNotify.OnMove()
    {
      return VSConstants.S_OK;
    }

























    int IVsWindowFrameNotify.OnShow(int fShow)
    {
      switch ((__FRAMESHOW)fShow)
      {
        case __FRAMESHOW.FRAMESHOW_WinShown:
        case __FRAMESHOW.FRAMESHOW_WinRestored:
          SetPropertyWindow();
          if (_warned == false)
          {
            _warned = true;
            MessageBox.Show(this, "The table designer is still in development.  Please report bugs to robert@blackcastlesoft.com", "Feature Under Review", MessageBoxButtons.OK);
          }
          break;
      }
      return VSConstants.S_OK;
    }

    int IVsWindowFrameNotify.OnSize()
    {
................................................................................
      return VSConstants.S_OK;
    }

    #endregion

    private void _dataGrid_CellEnter(object sender, DataGridViewCellEventArgs e)
    {
      try
      {
        if (e.ColumnIndex > -1)
        {
          _dataGrid.BeginEdit(true);
          _dataGrid_SelectionChanged(sender, e);
        }
      }
      catch
      {
      }
    }

    private void _dataGrid_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
      _dataGrid.EndEdit();
      if (e.Button == MouseButtons.Right)
................................................................................
      if (ispk == true)
      {
        e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
        _imageList.Draw(e.Graphics, e.CellBounds.Left, e.CellBounds.Top + ((e.CellBounds.Bottom - e.CellBounds.Top) - _imageList.ImageSize.Height) / 2, 0);
        e.Handled = true;
      }
    }

    private DataGridViewRow[] SelectedRows
    {
      get
      {
        List<DataGridViewRow> items = new List<DataGridViewRow>();

        for (int n = 0; n < _dataGrid.Rows.Count; n++)
        {
          if (_dataGrid.Rows[n].Selected || (_dataGrid.CurrentCell.RowIndex == n && _dataGrid.CurrentCell.Selected == true))
          {
            if (_dataGrid.Rows[n].Tag is Column)
              items.Add(_dataGrid.Rows[n]);
          }
        }

        DataGridViewRow[] objs = new DataGridViewRow[items.Count];
        items.CopyTo(objs);

        return objs;
      }
    }

    private void _dataGrid_SelectionChanged(object sender, EventArgs e)
    {
      if (_init == true) return;
      DataGridViewRow[] arr = SelectedRows;

      object[] objs = new object[arr.Length];

      for (int n = 0; n < objs.Length; n++)








        objs[n] = arr[n].Tag;

      _propertyGrid.SelectedObjects = objs;

      RefreshToolbars();




    }

    private void _dataGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
      if (_init == true) return;
      if (e.RowIndex > -1)
      {

        _propertyGrid.SelectedObjects = _propertyGrid.SelectedObjects;
      }
    }

    private void _dataGrid_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
    {
      if (_init == true) return;
      
      if (e.Row.Tag is Column)
        MakeDirty();

      _dataGrid_SelectionChanged(sender, e);
    }

    private void _dataGrid_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
    {
      if (_init == true) return;
      if (e.Row.Tag is Column)
      {
        _table.Columns.Remove(e.Row.Tag as Column);
      }
    }

    private void _dataGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    {



    }

    private void _dataGrid_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
    {


    }

    private Rectangle _dragBoxFromMouseDown;
    private int _rowIndexFromMouseDown;
    private int _rowIndexOfItemUnderMouseToDrop;

    private void _dataGrid_DragDrop(object sender, DragEventArgs e)
    {
      // The mouse locations are relative to the screen, so they must be 
      // converted to client coordinates.
      Point clientPoint = _dataGrid.PointToClient(new Point(e.X, e.Y));

      if (_rowIndexOfItemUnderMouseToDrop != -1)
        _dataGrid.Rows[_rowIndexOfItemUnderMouseToDrop].DividerHeight = 0;

      _rowIndexOfItemUnderMouseToDrop = _dataGrid.HitTest(clientPoint.X, clientPoint.Y).RowIndex;

      if (_rowIndexOfItemUnderMouseToDrop != -1)
        _dataGrid.Rows[_rowIndexOfItemUnderMouseToDrop].DividerHeight = 0;

      // If the drag operation was a move then remove and insert the row.
      if (e.Effect == DragDropEffects.Move)
      {
        DataGridViewRow[] rowsToMove = e.Data.GetData(typeof(DataGridViewRow[])) as DataGridViewRow[];
        for (int n = 0; n < rowsToMove.Length; n++)
        {
          _dataGrid.Rows.Remove(rowsToMove[n]);
          _table.Columns.Remove(rowsToMove[n].Tag as Column);
          _dataGrid.Rows.Insert(_rowIndexOfItemUnderMouseToDrop, rowsToMove[n]);
          _table.Columns.Insert(_rowIndexOfItemUnderMouseToDrop, rowsToMove[n].Tag as Column);
        }
        MakeDirty();
        RefreshToolbars();
      }
    }


    private void _dataGrid_DragOver(object sender, DragEventArgs e)
    {
      // The mouse locations are relative to the screen, so they must be 
      // converted to client coordinates.
      Point clientPoint = _dataGrid.PointToClient(new Point(e.X, e.Y));

      // Get the row index of the item the mouse is below. 
      if (_rowIndexOfItemUnderMouseToDrop != -1)
        _dataGrid.Rows[_rowIndexOfItemUnderMouseToDrop].DividerHeight = 0;

      _rowIndexOfItemUnderMouseToDrop = _dataGrid.HitTest(clientPoint.X, clientPoint.Y).RowIndex;

      if (_dataGrid.Rows[_rowIndexOfItemUnderMouseToDrop].IsNewRow == false && _rowIndexOfItemUnderMouseToDrop != _rowIndexFromMouseDown)
      {
        e.Effect = DragDropEffects.Move;

        if (_rowIndexOfItemUnderMouseToDrop != -1)
          _dataGrid.Rows[_rowIndexOfItemUnderMouseToDrop].DividerHeight = 3;
      }
      else
        e.Effect = DragDropEffects.None;
    }

    private void _dataGrid_MouseDown(object sender, MouseEventArgs e)
    {
      // Get the index of the item the mouse is below.
      _rowIndexFromMouseDown = _dataGrid.HitTest(e.X, e.Y).RowIndex;

      if (_rowIndexFromMouseDown != -1)
      {
        // Remember the point where the mouse down occurred. 
        // The DragSize indicates the size that the mouse can move 
        // before a drag event should be started. 
        Size dragSize = SystemInformation.DragSize;

        // Create a rectangle using the DragSize, with the mouse position being
        // at the center of the rectangle.
        _dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize);
      }
      else
        // Reset the rectangle if the mouse is not over an item in the ListBox.
        _dragBoxFromMouseDown = Rectangle.Empty;
    }

    private void _dataGrid_MouseMove(object sender, MouseEventArgs e)
    {
      if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
      {
        // If the mouse moves outside the rectangle, start the drag.
        if (_dragBoxFromMouseDown != Rectangle.Empty && !_dragBoxFromMouseDown.Contains(e.X, e.Y))
        {
          _rowIndexOfItemUnderMouseToDrop = -1;
          _dataGrid.EndEdit();
          // Proceed with the drag and drop, passing in the list item. 
          DragDropEffects dropEffect = _dataGrid.DoDragDrop(SelectedRows, DragDropEffects.Move);
        }
      }
    }

    private void _dataGrid_CellValidated(object sender, DataGridViewCellEventArgs e)
    {
      DataGridViewRow row = _dataGrid.Rows[e.RowIndex];
      Column col = row.Tag as Column;

      if (col == null && row.IsNewRow == false)
      {
        col = new Column(_table, row);
        row.Tag = col;
        _table.Columns.Insert(row.Index, col);
        _dataGrid_SelectionChanged(this, new EventArgs());
      }
      if (col != null)
        col.CellValueChanged(e.RowIndex, e.ColumnIndex);

      RefreshToolbars();
    }
  }

  internal class EditorHolder
  {
    private List<Index> _indexes;
    private List<ForeignKey> _fkeys;
    private List<string> _check;
    private List<Trigger> _triggers;


    internal EditorHolder(Table tbl)
    {
      _indexes = tbl.Indexes;
      _fkeys = tbl.ForeignKeys;
      _check = tbl.Check;
      _triggers = tbl.Triggers as List<Trigger>;
    }

    public List<Index> Indexes
    {
      get { return _indexes; }
    }

    public List<ForeignKey> ForeignKeys
    {
      get { return _fkeys; }
    }

    public List<string> Check
    {
      get { return _check; }
    }

    public List<Trigger> Triggers
    {
      get { return _triggers; }
    }
  }

  public class DesignerDocBase : UserControl
  {
    public virtual string CanonicalName
    {
      get
................................................................................
          pvar = 0;
          break;
        case __VSHPROPID.VSHPROPID_IconHandle:
          pvar = null;
          return VSConstants.S_OK;
      }








      if (pvar == null)
        return _owner.GetProperty(itemid, propid, out pvar);
      else
        return VSConstants.S_OK;
    }

    int IVsUIHierarchy.GetSite(out Microsoft.VisualStudio.OLE.Interop.IServiceProvider ppSP)

Changes to SQLite.Designer/Editors/TableDesignerDoc.resx.

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
...
149
150
151
152
153
154
155
156
157
158
159
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <metadata name="_splitter.GenerateMember" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <value>False</value>
  </metadata>
  <metadata name="splitContainer1.GenerateMember" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <value>False</value>
  </metadata>
  <metadata name="name.UserAddedColumn" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <value>True</value>
  </metadata>
  <metadata name="type.UserAddedColumn" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <value>True</value>
  </metadata>
  <metadata name="isnull.UserAddedColumn" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
................................................................................
        Ae8BLgFhAXsBjQHlAfEBrgH4Af8BBQFCAV//AMwAAUcBkAGpAZ8B9QH/Aa4B+gH/AZIB5wHwAbEB+gH/
        AYoB6QH1AQQBSgFo/wDMAAHTAdsB3wFpAbYBygFSAZwBswE5AYABmgElAW8BkAEZAWoBjgHWAd0B4f8A
        /wD/AP8A/wD/AP8AGwABQgFNAT4HAAE+AwABKAMAAaADAAEQAwABAQEAAQEFAAFAAQEWAAP/AQAF/w8A
        Bf8PAAP/Af4BPw8AA/8B/gEfDwAD/wH+AR8PAAP/Af4BHw8AA/8B/gEfDwAD/wH8AR8PAAP/AfgBDw8A
        A/8B+AEPDwAD/wH4AQ8PAAP/AfgBDw8AA/8B+AEPDwAF/w8ABf8PAAX/DwAL
</value>
  </data>
  <metadata name="_timer.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
    <value>126, 17</value>
  </metadata>
</root>







<
<
<







 







<
<
<

116
117
118
119
120
121
122



123
124
125
126
127
128
129
...
146
147
148
149
150
151
152



153
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <metadata name="_splitter.GenerateMember" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <value>False</value>
  </metadata>



  <metadata name="name.UserAddedColumn" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <value>True</value>
  </metadata>
  <metadata name="type.UserAddedColumn" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <value>True</value>
  </metadata>
  <metadata name="isnull.UserAddedColumn" type="System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
................................................................................
        Ae8BLgFhAXsBjQHlAfEBrgH4Af8BBQFCAV//AMwAAUcBkAGpAZ8B9QH/Aa4B+gH/AZIB5wHwAbEB+gH/
        AYoB6QH1AQQBSgFo/wDMAAHTAdsB3wFpAbYBygFSAZwBswE5AYABmgElAW8BkAEZAWoBjgHWAd0B4f8A
        /wD/AP8A/wD/AP8AGwABQgFNAT4HAAE+AwABKAMAAaADAAEQAwABAQEAAQEFAAFAAQEWAAP/AQAF/w8A
        Bf8PAAP/Af4BPw8AA/8B/gEfDwAD/wH+AR8PAAP/Af4BHw8AA/8B/gEfDwAD/wH8AR8PAAP/AfgBDw8A
        A/8B+AEPDwAD/wH4AQ8PAAP/AfgBDw8AA/8B+AEPDwAF/w8ABf8PAAX/DwAL
</value>
  </data>



</root>

Changes to SQLite.Designer/Editors/ViewDesignerDoc.Designer.cs.

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
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.components = new System.ComponentModel.Container();
      this._timer = new System.Windows.Forms.Timer(this.components);
      this._check = new System.Windows.Forms.Timer(this.components);

      this.SuspendLayout();
      // 
      // _timer
      // 
      this._timer.Tick += new System.EventHandler(this._timer_Tick);
      // 
      // _check
      // 
      this._check.Interval = 200;
      this._check.Tick += new System.EventHandler(this._check_Tick);
      // 










      // ViewDesignerDoc
      // 
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

      this.Name = "ViewDesignerDoc";
      this.Size = new System.Drawing.Size(553, 407);
      this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.Timer _timer;
    private System.Windows.Forms.Timer _check;

  }
}







>











>
>
>
>
>
>
>
>
>
>




>










>


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
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
      this.components = new System.ComponentModel.Container();
      this._timer = new System.Windows.Forms.Timer(this.components);
      this._check = new System.Windows.Forms.Timer(this.components);
      this._pg = new System.Windows.Forms.PropertyGrid();
      this.SuspendLayout();
      // 
      // _timer
      // 
      this._timer.Tick += new System.EventHandler(this._timer_Tick);
      // 
      // _check
      // 
      this._check.Interval = 200;
      this._check.Tick += new System.EventHandler(this._check_Tick);
      // 
      // _pg
      // 
      this._pg.Location = new System.Drawing.Point(0, 3);
      this._pg.Name = "_pg";
      this._pg.PropertySort = System.Windows.Forms.PropertySort.NoSort;
      this._pg.Size = new System.Drawing.Size(130, 130);
      this._pg.TabIndex = 2;
      this._pg.ToolbarVisible = false;
      this._pg.Visible = false;
      // 
      // ViewDesignerDoc
      // 
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
      this.Controls.Add(this._pg);
      this.Name = "ViewDesignerDoc";
      this.Size = new System.Drawing.Size(553, 407);
      this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.Timer _timer;
    private System.Windows.Forms.Timer _check;
    private System.Windows.Forms.PropertyGrid _pg;
  }
}

Changes to SQLite.Designer/Editors/ViewDesignerDoc.cs.








1
2
3
4
5
6
7
..
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
..
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
...
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
...
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
...
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
...
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
...
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
...
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
...
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
...
688
689
690
691
692
693
694


695


696
697
698


699
700
701
702
703
704
705
...
748
749
750
751
752
753
754
755






















namespace SQLite.Designer.Editors
{
  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Data.Common;
................................................................................
    internal bool _dirty = false;
    internal UserControl _queryDesigner;
    internal Type _typeQB;
    internal SQLite.Designer.Design.View _view;
    internal IOleCommandTarget _qbole;
    internal IOleInPlaceActiveObject _qbbase;
    private IntPtr _qbsql;




    public delegate bool EnumWindowsCallback(IntPtr hwnd, IntPtr lParam);
    [DllImport("user32.Dll")]
    public static extern bool EnumChildWindows(IntPtr parentHandle, EnumWindowsCallback callback, IntPtr lParam);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
................................................................................

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern int GetWindowTextLength(IntPtr hWnd);

    public ViewDesignerDoc(DataConnection cnn, string viewName)
    {

      _connection = cnn;

      InitializeComponent();

      _init = true;
      try
      {
        _typeQB = SQLiteDataAdapterToolboxItem._vsdesigner.GetType("Microsoft.VSDesigner.Data.Design.QueryBuilderControl");

        if (_typeQB != null)
        {
          _queryDesigner = Activator.CreateInstance(_typeQB) as UserControl;
          _typeQB.InvokeMember("Provider", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.NonPublic, null, _queryDesigner, new object[] { "System.Data.SQLite" });
          _typeQB.InvokeMember("ConnectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.NonPublic, null, _queryDesigner, new object[] { cnn.ConnectionSupport.ConnectionString });
          _typeQB.InvokeMember("EnableMorphing", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.NonPublic, null, _queryDesigner, new object[] { false });
          Controls.Add(_queryDesigner);
          _queryDesigner.Dock = DockStyle.Fill;
          _queryDesigner.Visible = true;
        }

        StringBuilder tables = new StringBuilder();

        using (DataReader reader = cnn.Command.Execute("SELECT * FROM sqlite_master", 1, null, 30))
        {
          while (reader.Read())
          {
            tables.Append(reader.GetItem(2).ToString());
            tables.Append(",");
          }
        }
................................................................................
          {
            viewName = String.Format("View{0}", n);
            n++;
          } while (alltables.IndexOf(viewName + ",", StringComparison.OrdinalIgnoreCase) > -1 || _editingTables.ContainsValue(viewName));

          _editingTables.Add(GetHashCode(), viewName);
        }
        _view = new SQLite.Designer.Design.View(viewName, cnn.ConnectionSupport.ProviderObject as DbConnection, this);
      }
      finally
      {
        _init = false;
      }
    }

................................................................................
      }
    }

    public void NotifyChanges()
    {
      if (_serviceProvider == null) return;

      //_sqlText.Text = _table.GetSql();

      // Get a reference to the Running Document Table
      IVsRunningDocumentTable runningDocTable = (IVsRunningDocumentTable)_serviceProvider.GetService(typeof(SVsRunningDocumentTable));

      // Lock the document
      uint docCookie;
      IVsHierarchy hierarchy;
      uint itemID;
................................................................................
      {
        shell.UpdateDocDataIsDirtyFeedback(docCookie, (_dirty == true) ? 1 : 0);
      }

      // Unlock the document.
      // Note that we have to unlock the document even if the previous call failed.
      runningDocTable.UnlockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, docCookie);


      // Check ff the call to NotifyDocChanged failed.
      //ErrorHandler.ThrowOnFailure(hr);
    }

    #region IVsPersistDocData Members

................................................................................
            pfSaveCanceled = 1;
            return VSConstants.S_OK;
          }
          _view.Name = dlg.TableName;
        }
      }

      //_init = true;
      //for (int n = 0; n < _table.Columns.Count; n++)
      //{
      //  Column c = _table.Columns[n];
      //  if (String.IsNullOrEmpty(c.ColumnName) == true)
      //  {
      //    _dataGrid.Rows.Remove(c.Parent);
      //    _table.Columns.Remove(c);
      //    n--;
      //    continue;
      //  }
      //}

      //for (int n = 0; n < _dataGrid.Rows.Count; n++)
      //{
      //  if ((_dataGrid.Rows[n].Tag is Column) == false)
      //  {
      //    try
      //    {
      //      _dataGrid.Rows.RemoveAt(n);
      //    }
      //    catch
      //    {
      //    }
      //    n--;
      //  }
      //}
      //_init = false;

      string query = _typeQB.InvokeMember("SqlText", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty, null, _queryDesigner, null) as string;
      _view.SqlText = query;

      query = _view.GetSqlText();
      if (String.IsNullOrEmpty(query) == false)
      {
        using (DbTransaction trans = _view.GetConnection().BeginTransaction())
................................................................................
        }
      }

      _dirty = false;
      _view.Committed();
      NotifyChanges();



      return VSConstants.S_OK;
    }

    public int SetUntitledDocPath(string pszDocDataPath)
    {
      return ((IPersistFileFormat)this).InitNew(0);
    }
................................................................................

    #endregion

    #region IVsWindowPane Members

    public int ClosePane()
    {
      if (_serviceProvider != null)
      {
        EnvDTE.DTE dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE));

        //Show toolbar
        if (dte != null)
        {
          Microsoft.VisualStudio.CommandBars.CommandBars commandBars = (Microsoft.VisualStudio.CommandBars.CommandBars)dte.CommandBars;
          Microsoft.VisualStudio.CommandBars.CommandBar bar = commandBars["View Designer"];
          bar.Visible = false;
        }
      }
      this.Dispose(true);
      return VSConstants.S_OK;
    }

    public int CreatePaneWindow(IntPtr hwndParent, int x, int y, int cx, int cy, out IntPtr hwnd)
    {
      Win32Methods.SetParent(Handle, hwndParent);
................................................................................

      if (shell != null)
      {
        shell.UpdateCommandUI(1);
      }
    }

    //[DllImport("ole32.dll")]
    //static extern int CreateStreamOnHGlobal(IntPtr hGlobal, bool fDeleteOnRelease,
    //   out IStream ppstm);

    public int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp)
    {
      _serviceProvider = new MyServiceProvider(psp);
      System.Reflection.MethodInfo mi = _typeQB.GetMethod("Init", System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, new Type[] { typeof(System.IServiceProvider), typeof(string) }, null);
      mi.Invoke(_queryDesigner, new object[] { _serviceProvider, _view.SqlText });

      _qbole = _typeQB.InvokeMember("OleCommandTarget", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetProperty, null, _queryDesigner, null) as IOleCommandTarget;
................................................................................
      NotifyChanges();
    }

    #region IOleCommandTarget Members

    public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
    {
      //if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
      //{

      //  switch ((VSConstants.VSStd97CmdID)nCmdID)
      //  {
      //    case VSConstants.VSStd97CmdID.PrimaryKey:
      //      bool newVal = IsPkSelected();

      //      foreach (Column c in _propertyGrid.SelectedObjects)
      //      {
      //        c.PrimaryKey.Enabled = !newVal;
      //      }
      //      _dataGrid_SelectionChanged(this, EventArgs.Empty);
      //      MakeDirty();
      //      return VSConstants.S_OK;
      //  }
      //}
      //else 
      //if (pguidCmdGroup == SQLiteCommandHandler.guidDavinci)
      //{
      //  switch ((VSConstants.VSStd97CmdID)nCmdID)
      //  {
      //    case VSConstants.VSStd97CmdID.ManageIndexes:
      //      IndexHolder holder = new IndexHolder(_table.Indexes, _table.ForeignKeys);


      //      _pg.SelectedObject = holder;
      //      _pg.SelectedGridItem = _pg.SelectedGridItem.Parent.GridItems[0];
      //      IndexEditor ed = new IndexEditor(_table);

      //      ed.EditValue((ITypeDescriptorContext)_pg.SelectedGridItem, (System.IServiceProvider)_pg.SelectedGridItem, _pg.SelectedGridItem.Value);
      //      return VSConstants.S_OK;
      //    case VSConstants.VSStd97CmdID.ManageRelationships:
      //      holder = new IndexHolder(_table.Indexes, _table.ForeignKeys);
      //      _pg.SelectedObject = holder;
      //      _pg.SelectedGridItem = _pg.SelectedGridItem.Parent.GridItems[1];
      //      ForeignKeyEditor fed = new ForeignKeyEditor(_table);
      //      fed.EditValue((ITypeDescriptorContext)_pg.SelectedGridItem, (System.IServiceProvider)_pg.SelectedGridItem, _pg.SelectedGridItem.Value);
      //      return VSConstants.S_OK;
      //    case VSConstants.VSStd97CmdID.AlignRight: // Insert Column
      //      _dataGrid.Rows.Insert(_dataGrid.SelectedRows[0].Index, 1);
      //      return VSConstants.S_OK;
      //    case VSConstants.VSStd97CmdID.AlignToGrid: // Delete Column
      //      while (_dataGrid.SelectedRows.Count > 0)
      //      {
      //        try
      //        {
      //          DataGridViewRow row = _dataGrid.SelectedRows[0];
      //          Column c = row.Tag as Column;
      //          row.Selected = false;
      //          if (c != null)
      //            _table.Columns.Remove(c);

      //          _dataGrid.Rows.Remove(row);
      //        }
      //        catch
      //        {
      //        }
      //      }
      //      return VSConstants.S_OK;
      //  }
      //}



      if (_qbole != null) return _qbole.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);

      return (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
    }

    public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
    {
      //if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
      //{


      //  switch ((VSConstants.VSStd97CmdID)prgCmds[0].cmdID)
      //  {
      //    case VSConstants.VSStd97CmdID.PrimaryKey:
      //      prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
      //      if (IsPkSelected() == true)
      //        prgCmds[0].cmdf |= (uint)(OLECMDF.OLECMDF_LATCHED);

      //      break;
      //    //case VSConstants.VSStd97CmdID.GenerateChangeScript:

      //    //  prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
      //    //  break;
      //    default:
      //      return (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
      //  }
      //  return VSConstants.S_OK;
      //}

      //if (pguidCmdGroup == SQLiteCommandHandler.guidDavinci)
      //{
      //  switch (prgCmds[0].cmdID)
      //  {
      //    //case (uint)VSConstants.VSStd97CmdID.ManageRelationships:
      //    //case (uint)VSConstants.VSStd97CmdID.ManageIndexes:
      //    //case (uint)VSConstants.VSStd97CmdID.ManageConstraints:
      //    //case 10: // Table View -> Custom
      //    //case 14: // Table View -> Modify Custom
      //    //case 33: // Database Diagram -> Add Table
      //    //case 1: // Database Diagram -> Add Related Tables
      //    //case 12: // Database Diagram -> Delete From Database
      //    //case 51: // Database Diagram -> Remove From Diagram
      //    //case 13: // Database Diagram -> Autosize Selected Tables
      //    //case 3: // Database Diagram -> Arrange Selection
      //    //case 2: // Database Diagram -> Arrange Tables
      //    //case 16: // Database Diagram -> Zoom -> 200%
      //    //case 17: // Database Diagram -> Zoom -> 150%
      //    //case 18: // Database Diagram -> Zoom -> 100%
      //    //case 19: // Database Diagram -> Zoom -> 75%
      //    //case 20: // Database Diagram -> Zoom -> 50%
      //    //case 21: // Database Diagram -> Zoom -> 25%
      //    //case 22: // Database Diagram -> Zoom -> 10%
      //    //case 24: // Database Diagram -> Zoom -> To Fit
      //    //case 6: // Database Diagram -> New Text Annotation
      //    //case 15: // Database Diagram -> Set Text Annotation Font
      //    //case 7: // Database Diagram -> Show Relationship Labels
      //    //case 8: // Database Diagram -> View Page Breaks
      //    //case 9: // Database Diagram -> Recalculate Page Breaks
      //    //case 43: // Database Diagram -> Copy Diagram to Clipboard
      //    //case 41: // Query Designer -> Table Display -> Column Names
      //    //case 42: // Query Designer -> Table Display -> Name Only
      //    //case 39: // Query Designer -> Add Table
      //    //case 4: // Insert Column
      //    //case 5: // Delete Column
      //    //  prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);
      //    //  break;
      //    default:
      //      return (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
      //  }
      //  return VSConstants.S_OK;
      //}



      int retval = (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
      
      if (_qbole != null)
        retval = _qbole.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);

      //if (pguidCmdGroup == SQLiteCommandHandler.guidQueryGroup)
................................................................................
    private void _timer_Tick(object sender, EventArgs e)
    {
      _timer.Enabled = false;
      if (_serviceProvider != null)
      {
        EnvDTE.DTE dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE));

        //Show toolbar
        if (dte != null)
        {
          Microsoft.VisualStudio.CommandBars.CommandBars commandBars = (Microsoft.VisualStudio.CommandBars.CommandBars)dte.CommandBars;
          Microsoft.VisualStudio.CommandBars.CommandBar bar = commandBars["View Designer"];
          bar.Visible = true;
        }

        if (_qdinit == false)
        {
          _qdinit = true;
          _init = true;
          try
          {
            _typeQB.InvokeMember("PostInit", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.InvokeMethod, null, _queryDesigner, null);
................................................................................
    }

    int IVsWindowFrameNotify.OnShow(int fShow)
    {
      switch ((__FRAMESHOW)fShow)
      {
        case __FRAMESHOW.FRAMESHOW_WinShown:


          SetPropertyWindow();


          _timer.Enabled = true;
          break;
        case __FRAMESHOW.FRAMESHOW_WinHidden:


          break;
      }
      return VSConstants.S_OK;
    }

    int IVsWindowFrameNotify.OnSize()
    {
................................................................................
    }

    protected override object GetServiceImpl(Type serviceType)
    {
      return this.GetService(serviceType.GUID);
    }
  }
}















>
>
>
>
>
>
>







 







>
>
>







 







|

>
|
>











|








|







 







|







 







<
<







 







<







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>
>







 







<
<
<
<
<
<
<
<
<
<
<
<







 







<
<
<
<







 







|
<
>
|
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>
>
|
|
<
>
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
|
>
>







<
<
>
>
|
<
<
<
<
<
|
<
<
>
|
<
<
<
<
|
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>
>







 







<
<
<
<
<
<
<
<







 







>
>

>
>
|
<
<
>
>







 







|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
..
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
...
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
...
180
181
182
183
184
185
186


187
188
189
190
191
192
193
...
207
208
209
210
211
212
213

214
215
216
217
218
219
220
...
274
275
276
277
278
279
280





























281
282
283
284
285
286
287
...
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
...
365
366
367
368
369
370
371




372
373
374
375
376
377
378
...
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
...
520
521
522
523
524
525
526








527
528
529
530
531
532
533
...
551
552
553
554
555
556
557
558
559
560
561
562
563


564
565
566
567
568
569
570
571
572
...
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/

namespace SQLite.Designer.Editors
{
  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Data.Common;
................................................................................
    internal bool _dirty = false;
    internal UserControl _queryDesigner;
    internal Type _typeQB;
    internal SQLite.Designer.Design.View _view;
    internal IOleCommandTarget _qbole;
    internal IOleInPlaceActiveObject _qbbase;
    private IntPtr _qbsql;
    internal DataViewHierarchyAccessor _accessor;
    internal int _itemId;
    static private bool _warned = false;

    public delegate bool EnumWindowsCallback(IntPtr hwnd, IntPtr lParam);
    [DllImport("user32.Dll")]
    public static extern bool EnumChildWindows(IntPtr parentHandle, EnumWindowsCallback callback, IntPtr lParam);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
................................................................................

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern int GetWindowTextLength(IntPtr hWnd);

    public ViewDesignerDoc(int itemId, DataViewHierarchyAccessor accessor, string viewName)
    {
      _accessor = accessor;
      _connection = accessor.Connection;
      _itemId = itemId;
      InitializeComponent();

      _init = true;
      try
      {
        _typeQB = SQLiteDataAdapterToolboxItem._vsdesigner.GetType("Microsoft.VSDesigner.Data.Design.QueryBuilderControl");

        if (_typeQB != null)
        {
          _queryDesigner = Activator.CreateInstance(_typeQB) as UserControl;
          _typeQB.InvokeMember("Provider", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.NonPublic, null, _queryDesigner, new object[] { "System.Data.SQLite" });
          _typeQB.InvokeMember("ConnectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.NonPublic, null, _queryDesigner, new object[] { _connection.ConnectionSupport.ConnectionString });
          _typeQB.InvokeMember("EnableMorphing", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.NonPublic, null, _queryDesigner, new object[] { false });
          Controls.Add(_queryDesigner);
          _queryDesigner.Dock = DockStyle.Fill;
          _queryDesigner.Visible = true;
        }

        StringBuilder tables = new StringBuilder();

        using (DataReader reader = _connection.Command.Execute("SELECT * FROM sqlite_master", 1, null, 30))
        {
          while (reader.Read())
          {
            tables.Append(reader.GetItem(2).ToString());
            tables.Append(",");
          }
        }
................................................................................
          {
            viewName = String.Format("View{0}", n);
            n++;
          } while (alltables.IndexOf(viewName + ",", StringComparison.OrdinalIgnoreCase) > -1 || _editingTables.ContainsValue(viewName));

          _editingTables.Add(GetHashCode(), viewName);
        }
        _view = new SQLite.Designer.Design.View(viewName, _connection.ConnectionSupport.ProviderObject as DbConnection, this);
      }
      finally
      {
        _init = false;
      }
    }

................................................................................
      }
    }

    public void NotifyChanges()
    {
      if (_serviceProvider == null) return;



      // Get a reference to the Running Document Table
      IVsRunningDocumentTable runningDocTable = (IVsRunningDocumentTable)_serviceProvider.GetService(typeof(SVsRunningDocumentTable));

      // Lock the document
      uint docCookie;
      IVsHierarchy hierarchy;
      uint itemID;
................................................................................
      {
        shell.UpdateDocDataIsDirtyFeedback(docCookie, (_dirty == true) ? 1 : 0);
      }

      // Unlock the document.
      // Note that we have to unlock the document even if the previous call failed.
      runningDocTable.UnlockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, docCookie);


      // Check ff the call to NotifyDocChanged failed.
      //ErrorHandler.ThrowOnFailure(hr);
    }

    #region IVsPersistDocData Members

................................................................................
            pfSaveCanceled = 1;
            return VSConstants.S_OK;
          }
          _view.Name = dlg.TableName;
        }
      }






























      string query = _typeQB.InvokeMember("SqlText", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty, null, _queryDesigner, null) as string;
      _view.SqlText = query;

      query = _view.GetSqlText();
      if (String.IsNullOrEmpty(query) == false)
      {
        using (DbTransaction trans = _view.GetConnection().BeginTransaction())
................................................................................
        }
      }

      _dirty = false;
      _view.Committed();
      NotifyChanges();

      SQLiteCommandHandler.Refresh(_accessor, _itemId);

      return VSConstants.S_OK;
    }

    public int SetUntitledDocPath(string pszDocDataPath)
    {
      return ((IPersistFileFormat)this).InitNew(0);
    }
................................................................................

    #endregion

    #region IVsWindowPane Members

    public int ClosePane()
    {












      this.Dispose(true);
      return VSConstants.S_OK;
    }

    public int CreatePaneWindow(IntPtr hwndParent, int x, int y, int cx, int cy, out IntPtr hwnd)
    {
      Win32Methods.SetParent(Handle, hwndParent);
................................................................................

      if (shell != null)
      {
        shell.UpdateCommandUI(1);
      }
    }





    public int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp)
    {
      _serviceProvider = new MyServiceProvider(psp);
      System.Reflection.MethodInfo mi = _typeQB.GetMethod("Init", System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, new Type[] { typeof(System.IServiceProvider), typeof(string) }, null);
      mi.Invoke(_queryDesigner, new object[] { _serviceProvider, _view.SqlText });

      _qbole = _typeQB.InvokeMember("OleCommandTarget", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetProperty, null, _queryDesigner, null) as IOleCommandTarget;
................................................................................
      NotifyChanges();
    }

    #region IOleCommandTarget Members

    public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
    {
      if (pguidCmdGroup == SQLiteCommandHandler.guidSQLiteCmdSet)

      {
        switch ((cmdid)nCmdID)



        {
















          case cmdid.Triggers:
            ViewHolder holder = new ViewHolder(_view);
            _pg.SelectedObject = holder;
            _pg.SelectedGridItem = _pg.SelectedGridItem.Parent.GridItems[0];

            TriggerEditor ted = new TriggerEditor(_view);
            ted.EditValue((ITypeDescriptorContext)_pg.SelectedGridItem, (System.IServiceProvider)_pg.SelectedGridItem, _pg.SelectedGridItem.Value);
            return VSConstants.S_OK;




















        }









      }


      if (_qbole != null) return _qbole.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);

      return (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
    }

    public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
    {


      if (pguidCmdGroup == SQLiteCommandHandler.guidSQLiteCmdSet)
      {
        switch (prgCmds[0].cmdID)





        {


          case (uint)cmdid.Triggers:
            prgCmds[0].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED);




            return VSConstants.S_OK;

        }










































      }


      int retval = (int)(Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED);
      
      if (_qbole != null)
        retval = _qbole.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);

      //if (pguidCmdGroup == SQLiteCommandHandler.guidQueryGroup)
................................................................................
    private void _timer_Tick(object sender, EventArgs e)
    {
      _timer.Enabled = false;
      if (_serviceProvider != null)
      {
        EnvDTE.DTE dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE));









        if (_qdinit == false)
        {
          _qdinit = true;
          _init = true;
          try
          {
            _typeQB.InvokeMember("PostInit", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.InvokeMethod, null, _queryDesigner, null);
................................................................................
    }

    int IVsWindowFrameNotify.OnShow(int fShow)
    {
      switch ((__FRAMESHOW)fShow)
      {
        case __FRAMESHOW.FRAMESHOW_WinShown:
        case __FRAMESHOW.FRAMESHOW_WinRestored:
          _timer.Enabled = true;
          SetPropertyWindow();
          if (_warned == false)
          {
            _warned = true;


            MessageBox.Show(this, "The view designer is still in development.  Please report bugs to robert@blackcastlesoft.com", "Feature Under Review", MessageBoxButtons.OK);
          }
          break;
      }
      return VSConstants.S_OK;
    }

    int IVsWindowFrameNotify.OnSize()
    {
................................................................................
    }

    protected override object GetServiceImpl(Type serviceType)
    {
      return this.GetService(serviceType.GUID);
    }
  }

  internal class ViewHolder
  {
    private List<ViewTrigger> _triggers;

    internal ViewHolder(SQLite.Designer.Design.View parent)
    {
      _triggers = parent.Triggers as List<ViewTrigger>;
    }

    public List<ViewTrigger> Triggers
    {
      get { return _triggers; }
    }
  }
}

Changes to SQLite.Designer/PkgCmd.vsct.

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
<?xml version="1.0" encoding="utf-8"?>
<CommandTable language="en-US" xmlns="http://schemas.microsoft.com/VisualStudio/2005-10-18/CommandTable">

  <Commands package="guidVSPackageBasedProviderPkg">
    <Buttons>

      <Button guid="guidVSPackageBasedProviderCmdSet" id="cmdidVacuum" type="Button">
        <CommandFlag>DefaultInvisible</CommandFlag>
        <CommandFlag>DynamicVisibility</CommandFlag>
        <CommandFlag>DefaultDisabled</CommandFlag>
        <Strings>
          <ButtonText>&amp;Vacuum</ButtonText>
        </Strings>
      </Button>

      <Button guid="guidVSPackageBasedProviderCmdSet" id="cmdidRekey" type="Button">
        <CommandFlag>DefaultInvisible</CommandFlag>
        <CommandFlag>DynamicVisibility</CommandFlag>
        <CommandFlag>DefaultDisabled</CommandFlag>
        <Strings>
          <ButtonText>Change &amp;Password ...</ButtonText>
        </Strings>
      </Button>













    </Buttons>
  </Commands>
  <CommandPlacements>
    <CommandPlacement guid="guidVSPackageBasedProviderCmdSet" id="cmdidVacuum" priority="0x0100">
      <Parent guid="guidVSData" id="IDG_DV_CONNECTION" />
    </CommandPlacement>
    <CommandPlacement guid="guidVSPackageBasedProviderCmdSet" id="cmdidRekey" priority="0x0100">
      <Parent guid="guidVSData" id="IDG_DV_CONNECTION" />
    </CommandPlacement>










  </CommandPlacements>
  <Symbols>
    <GuidSymbol name="Group_Undefined" value="{83285929-227c-11d3-b870-00c04f79f802}" />
    <GuidSymbol name="Pkg_Undefined" value="{8328592a-227c-11d3-b870-00c04f79f802}" />
    <GuidSymbol name="guidVSPackageBasedProviderPkg" value="{dcbe6c8d-0e57-4099-a183-98ff74c64d9c}" />
    <GuidSymbol name="guidVSData" value="{4614107f-217d-4bbf-9dfe-b9e165c65572}">
      <IDSymbol name="IDG_DV_CONNECTION" value="0x4101" />
    </GuidSymbol>
    <GuidSymbol name="guidVSPackageBasedProviderCmdSet" value="{814658ee-a28e-4b97-bc33-4b1bc81ebecb}">
      <IDSymbol name="cmdidRekey" value="0x0107" />
      <IDSymbol name="cmdidVacuum" value="0x0106" />

    </GuidSymbol>
    <GuidSymbol name="guidOfficeIcon" value="{d309f794-903f-11d0-9efc-00a0c911004f}">
      <IDSymbol name="msotcidNoIcon" value="0x02EA" />
    </GuidSymbol>
  </Symbols>
</CommandTable>


>


>








>








>
>
>
>
>
>
>
>
>
>
>
>
>









>
>
>
>
>
>
>
>
>
>
|










>






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
<?xml version="1.0" encoding="utf-8"?>
<CommandTable language="en-US" xmlns="http://schemas.microsoft.com/VisualStudio/2005-10-18/CommandTable">
  <Extern href="PkgCmd.h" />
  <Commands package="guidVSPackageBasedProviderPkg">
    <Buttons>
      
      <Button guid="guidVSPackageBasedProviderCmdSet" id="cmdidVacuum" type="Button">
        <CommandFlag>DefaultInvisible</CommandFlag>
        <CommandFlag>DynamicVisibility</CommandFlag>
        <CommandFlag>DefaultDisabled</CommandFlag>
        <Strings>
          <ButtonText>&amp;Vacuum</ButtonText>
        </Strings>
      </Button>
      
      <Button guid="guidVSPackageBasedProviderCmdSet" id="cmdidRekey" type="Button">
        <CommandFlag>DefaultInvisible</CommandFlag>
        <CommandFlag>DynamicVisibility</CommandFlag>
        <CommandFlag>DefaultDisabled</CommandFlag>
        <Strings>
          <ButtonText>Change &amp;Password ...</ButtonText>
        </Strings>
      </Button>

      <Button guid="guidVSPackageBasedProviderCmdSet" id="cmdidTriggers" priority="0x0700" type="Button">
        <Icon guid="guidSharedBmps8" id="bmpid8LayoutDiagram"/>
        <CommandFlag>DynamicVisibility</CommandFlag>
        <CommandFlag>DefaultInvisible</CommandFlag>
        <CommandFlag>DefaultDisabled</CommandFlag>
        <Strings>
          <ButtonText>Manage &amp;Triggers</ButtonText>
          <ToolTipText>Manage Triggers</ToolTipText>
          <CommandName>Manage Triggers</CommandName>
        </Strings>
      </Button>

    </Buttons>
  </Commands>
  <CommandPlacements>
    <CommandPlacement guid="guidVSPackageBasedProviderCmdSet" id="cmdidVacuum" priority="0x0100">
      <Parent guid="guidVSData" id="IDG_DV_CONNECTION" />
    </CommandPlacement>
    <CommandPlacement guid="guidVSPackageBasedProviderCmdSet" id="cmdidRekey" priority="0x0100">
      <Parent guid="guidVSData" id="IDG_DV_CONNECTION" />
    </CommandPlacement>

    <CommandPlacement guid="guidVSPackageBasedProviderCmdSet" id="cmdidTriggers" priority="0x0700">
      <Parent guid="guidDavDataGrpId" id="IDG_SCH_TOOLBAR_TABLEOPS" />
    </CommandPlacement>

    <CommandPlacement guid="guidVSPackageBasedProviderCmdSet" id="cmdidTriggers" priority="0x1000">
      <Parent guid="guidDavDataGrpId" id="IDG_QRY_TOOLBAR_VIEWSHAPE" />
    </CommandPlacement>


  </CommandPlacements>  
  <Symbols>
    <GuidSymbol name="Group_Undefined" value="{83285929-227c-11d3-b870-00c04f79f802}" />
    <GuidSymbol name="Pkg_Undefined" value="{8328592a-227c-11d3-b870-00c04f79f802}" />
    <GuidSymbol name="guidVSPackageBasedProviderPkg" value="{dcbe6c8d-0e57-4099-a183-98ff74c64d9c}" />
    <GuidSymbol name="guidVSData" value="{4614107f-217d-4bbf-9dfe-b9e165c65572}">
      <IDSymbol name="IDG_DV_CONNECTION" value="0x4101" />
    </GuidSymbol>
    <GuidSymbol name="guidVSPackageBasedProviderCmdSet" value="{814658ee-a28e-4b97-bc33-4b1bc81ebecb}">
      <IDSymbol name="cmdidRekey" value="0x0107" />
      <IDSymbol name="cmdidVacuum" value="0x0106" />
      <IDSymbol name="cmdidTriggers" value="0x0108" />
    </GuidSymbol>
    <GuidSymbol name="guidOfficeIcon" value="{d309f794-903f-11d0-9efc-00a0c911004f}">
      <IDSymbol name="msotcidNoIcon" value="0x02EA" />
    </GuidSymbol>
  </Symbols>
</CommandTable>

Added SQLite.Designer/Pkgcmd.h.

























>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
#ifndef _PKGCMDS_
#define _PKGCMDS_

#define guidSharedBmps8                             {2b671d3d-ab51-434a-8d38-cbf1728530bb}
#define guidDavDataGrpId                            {732abe74-cd80-11d0-a2db-00aa00a3efff}
#define GUID_Mode_TableDesigner                     {4194fee5-6777-419f-a5fc-47a536df1bdb}

#define bmpid8LayoutDiagram                         0x0004
#define IDG_SCH_TOOLBAR_TABLEOPS                    0x1110
#define IDG_QRY_TOOLBAR_VIEWSHAPE                   0x1012

#endif

Added SQLite.Designer/Resources/info.png.

cannot compute difference between binary files

Changes to SQLite.Designer/SQLite.Designer.csproj.

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
..
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
..
92
93
94
95
96
97
98







99
100
101
102

103

104
105
106
107
108
109
110
...
184
185
186
187
188
189
190



191
192
193



194
195
196
197
198
199
200
201
202
203
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>..\bin\designer\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <NoWarn>1701;1702;1699</NoWarn>
    <FileAlignment>512</FileAlignment>
    <PlatformTarget>x86</PlatformTarget>
    <AllowUnsafeBlocks>false</AllowUnsafeBlocks>
    <RegisterOutputPackage>false</RegisterOutputPackage>
    <GeneratePkgDefFile>false</GeneratePkgDefFile>
    <RegisterWithCodebase>false</RegisterWithCodebase>
  </PropertyGroup>
................................................................................
    <DebugType>none</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>..\bin\Designer\</OutputPath>
    <DefineConstants>
    </DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <NoWarn>1701;1702;1699</NoWarn>
    <FileAlignment>512</FileAlignment>
    <PlatformTarget>x86</PlatformTarget>
    <AllowUnsafeBlocks>false</AllowUnsafeBlocks>
    <RegisterOutputPackage>false</RegisterOutputPackage>
    <RegisterWithCodebase>false</RegisterWithCodebase>
    <GeneratePkgDefFile>false</GeneratePkgDefFile>
  </PropertyGroup>
................................................................................
  <ItemGroup>
    <Compile Include="ChangePasswordDialog.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Include="ChangePasswordDialog.Designer.cs">
      <DependentUpon>ChangePasswordDialog.cs</DependentUpon>
    </Compile>







    <Compile Include="Design\Column.cs" />
    <Compile Include="Design\ForeignKey.cs" />
    <Compile Include="Design\Index.cs" />
    <Compile Include="Design\PrimaryKey.cs" />

    <Compile Include="Design\Table.cs" />

    <Compile Include="Design\Unique.cs" />
    <Compile Include="Design\View.cs" />
    <Compile Include="Editors\AutoCompleteColumn.cs">
      <SubType>Component</SubType>
    </Compile>
    <Compile Include="Editors\TableDesignerDoc.cs">
      <SubType>UserControl</SubType>
................................................................................
    </EmbeddedResource>
    <EmbeddedResource Include="SQLiteDataObjectSupport.xml" />
    <EmbeddedResource Include="TableNameDialog.resx">
      <DependentUpon>TableNameDialog.cs</DependentUpon>
    </EmbeddedResource>
  </ItemGroup>
  <ItemGroup>



    <EmbeddedResource Include="SQLiteDataViewSupport2005.xml" />
  </ItemGroup>
  <ItemGroup>



    <Folder Include="Properties\" />
    <Folder Include="Resources\" />
  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v9.0\VSSDK\Microsoft.VsSDK.targets" />
  <PropertyGroup>
    <PostBuildEvent>
    </PostBuildEvent>
  </PropertyGroup>
</Project>







|







 







|







 







>
>
>
>
>
>
>




>

>







 







>
>
>



>
>
>

<








23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
..
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
..
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
...
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
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>..\bin\designer\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <NoWarn>1701;1702;1699;3001</NoWarn>
    <FileAlignment>512</FileAlignment>
    <PlatformTarget>x86</PlatformTarget>
    <AllowUnsafeBlocks>false</AllowUnsafeBlocks>
    <RegisterOutputPackage>false</RegisterOutputPackage>
    <GeneratePkgDefFile>false</GeneratePkgDefFile>
    <RegisterWithCodebase>false</RegisterWithCodebase>
  </PropertyGroup>
................................................................................
    <DebugType>none</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>..\bin\Designer\</OutputPath>
    <DefineConstants>
    </DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <NoWarn>1701;1702;1699;3001</NoWarn>
    <FileAlignment>512</FileAlignment>
    <PlatformTarget>x86</PlatformTarget>
    <AllowUnsafeBlocks>false</AllowUnsafeBlocks>
    <RegisterOutputPackage>false</RegisterOutputPackage>
    <RegisterWithCodebase>false</RegisterWithCodebase>
    <GeneratePkgDefFile>false</GeneratePkgDefFile>
  </PropertyGroup>
................................................................................
  <ItemGroup>
    <Compile Include="ChangePasswordDialog.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Include="ChangePasswordDialog.Designer.cs">
      <DependentUpon>ChangePasswordDialog.cs</DependentUpon>
    </Compile>
    <Compile Include="ChangeScriptDialog.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Include="ChangeScriptDialog.Designer.cs">
      <DependentUpon>ChangeScriptDialog.cs</DependentUpon>
    </Compile>
    <Compile Include="Design\Check.cs" />
    <Compile Include="Design\Column.cs" />
    <Compile Include="Design\ForeignKey.cs" />
    <Compile Include="Design\Index.cs" />
    <Compile Include="Design\PrimaryKey.cs" />
    <Compile Include="Design\SimpleTokenizer.cs" />
    <Compile Include="Design\Table.cs" />
    <Compile Include="Design\Trigger.cs" />
    <Compile Include="Design\Unique.cs" />
    <Compile Include="Design\View.cs" />
    <Compile Include="Editors\AutoCompleteColumn.cs">
      <SubType>Component</SubType>
    </Compile>
    <Compile Include="Editors\TableDesignerDoc.cs">
      <SubType>UserControl</SubType>
................................................................................
    </EmbeddedResource>
    <EmbeddedResource Include="SQLiteDataObjectSupport.xml" />
    <EmbeddedResource Include="TableNameDialog.resx">
      <DependentUpon>TableNameDialog.cs</DependentUpon>
    </EmbeddedResource>
  </ItemGroup>
  <ItemGroup>
    <EmbeddedResource Include="ChangeScriptDialog.resx">
      <DependentUpon>ChangeScriptDialog.cs</DependentUpon>
    </EmbeddedResource>
    <EmbeddedResource Include="SQLiteDataViewSupport2005.xml" />
  </ItemGroup>
  <ItemGroup>
    <None Include="Resources\info.png" />
  </ItemGroup>
  <ItemGroup>
    <Folder Include="Properties\" />

  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v9.0\VSSDK\Microsoft.VsSDK.targets" />
  <PropertyGroup>
    <PostBuildEvent>
    </PostBuildEvent>
  </PropertyGroup>
</Project>

Changes to SQLite.Designer/SQLiteCommandHandler.cs.

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
...
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
...
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
...
384
385
386
387
388
389
390
391
392
393
394




395
396
397
398
399
  using SQLite.Designer.Editors;

  enum cmdid
  {
    CreateTable = 0x3520,
    CreateView = 0x3521,
    Alter = 0x3003,

    Delete = 17,
    Vacuum = 262,
    Rekey = 263,

  }

  internal sealed class SQLiteCommandHandler : DataViewCommandHandler
  {
    internal static readonly Guid guidDataCmdSet = new Guid("501822E1-B5AF-11d0-B4DC-00A0C91506EF");
    internal static readonly Guid guidSQLiteCmdSet = new Guid("814658EE-A28E-4b97-BC33-4B1BC81EBECB");
    internal static readonly Guid guidIFCmdId = new Guid("{74d21311-2aee-11d1-8bfb-00a0c90f26f7}");
    internal static readonly Guid guidDavinci = new Guid("{732abe75-cd80-11d0-a2db-00aa00a3efff}");
    internal static readonly Guid guidDavinciGrp = new Guid("{732abe74-cd80-11d0-a2db-00aa00a3efff}");
    internal static readonly Guid guidQueryGroup = new Guid("5efc7975-14bc-11cf-9b2b-00aa00573819");



    public SQLiteCommandHandler()
    {
    }

    public override OleCommandStatus GetCommandStatus(int[] itemIds, OleCommand command, OleCommandTextType textType, OleCommandStatus status)
    {
................................................................................
      Microsoft.VisualStudio.OLE.Interop.IServiceProvider provider = DataViewHierarchyAccessor.ServiceProvider as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
      IVsUIShell shell = DataViewHierarchyAccessor.ServiceProvider.GetService(typeof(IVsUIShell)) as IVsUIShell;
      IVsUIHierarchy hier = DataViewHierarchyAccessor.Hierarchy;
      IVsWindowFrame frame;

      if (shell != null)
      {
        TableDesignerDoc form = new TableDesignerDoc(DataViewHierarchyAccessor.Connection, tableName);
        IntPtr formptr = System.Runtime.InteropServices.Marshal.GetIUnknownForObject(form);
        Guid empty = Guid.Empty;
        FakeHierarchy fake = new FakeHierarchy(form, hier);

        int code = shell.CreateDocumentWindow(
          0, // (uint)(__VSCREATEDOCWIN.CDW_fCreateNewWindow | __VSCREATEDOCWIN.CDW_RDTFLAGS_MASK) | (uint)(_VSRDTFLAGS.RDT_CanBuildFromMemory | _VSRDTFLAGS.RDT_NonCreatable | _VSRDTFLAGS.RDT_VirtualDocument | _VSRDTFLAGS.RDT_DontAddToMRU),
          form.Name, fake, (uint)itemId, formptr, formptr, ref empty, null, ref empty, provider, "", form.Caption, null, out frame);

        if (frame != null)
        {
          object ret;
          int prop = (int)__VSFPROPID.VSFPROPID_Caption;
          
          code = frame.GetProperty(prop, out ret);
................................................................................
      Microsoft.VisualStudio.OLE.Interop.IServiceProvider provider = DataViewHierarchyAccessor.ServiceProvider as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
      IVsUIShell shell = DataViewHierarchyAccessor.ServiceProvider.GetService(typeof(IVsUIShell)) as IVsUIShell;
      IVsUIHierarchy hier = DataViewHierarchyAccessor.Hierarchy;
      IVsWindowFrame frame;

      if (shell != null)
      {
        ViewDesignerDoc form = new ViewDesignerDoc(DataViewHierarchyAccessor.Connection, viewName);
        IntPtr formptr = System.Runtime.InteropServices.Marshal.GetIUnknownForObject(form);
        Guid empty = Guid.Empty;
        FakeHierarchy fake = new FakeHierarchy(form, hier);

        int code = shell.CreateDocumentWindow(
          0, // (uint)(__VSCREATEDOCWIN.CDW_fCreateNewWindow | __VSCREATEDOCWIN.CDW_RDTFLAGS_MASK) | (uint)(_VSRDTFLAGS.RDT_CanBuildFromMemory | _VSRDTFLAGS.RDT_NonCreatable | _VSRDTFLAGS.RDT_VirtualDocument | _VSRDTFLAGS.RDT_DontAddToMRU),
          form.Name, fake, (uint)itemId, formptr, formptr, ref empty, null, ref empty, provider, "", form.Caption, null, out frame);

        if (frame != null)
        {
          object ret;
          int prop = (int)__VSFPROPID.VSFPROPID_Caption;

          code = frame.GetProperty(prop, out ret);
................................................................................

            Refresh(itemId);
          }
        }
      }
    }

    private void Refresh(int itemId)
    {
      IVsUIHierarchy hier = DataViewHierarchyAccessor.Hierarchy as IVsUIHierarchy;





      Guid g = VSConstants.GUID_VSStandardCommandSet97;
      hier.ExecCommand((uint)itemId, ref g, (uint)0xbd, (uint)OleCommandExecutionOption.DoDefault, IntPtr.Zero, IntPtr.Zero);
    }
  }
}







>



>










>
>







 







|






|







 







|






|







 







|

|
|
>
>
>
>





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
...
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
...
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
...
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
  using SQLite.Designer.Editors;

  enum cmdid
  {
    CreateTable = 0x3520,
    CreateView = 0x3521,
    Alter = 0x3003,
    Refresh = 0x3004,
    Delete = 17,
    Vacuum = 262,
    Rekey = 263,
    Triggers = 264,
  }

  internal sealed class SQLiteCommandHandler : DataViewCommandHandler
  {
    internal static readonly Guid guidDataCmdSet = new Guid("501822E1-B5AF-11d0-B4DC-00A0C91506EF");
    internal static readonly Guid guidSQLiteCmdSet = new Guid("814658EE-A28E-4b97-BC33-4B1BC81EBECB");
    internal static readonly Guid guidIFCmdId = new Guid("{74d21311-2aee-11d1-8bfb-00a0c90f26f7}");
    internal static readonly Guid guidDavinci = new Guid("{732abe75-cd80-11d0-a2db-00aa00a3efff}");
    internal static readonly Guid guidDavinciGrp = new Guid("{732abe74-cd80-11d0-a2db-00aa00a3efff}");
    internal static readonly Guid guidQueryGroup = new Guid("5efc7975-14bc-11cf-9b2b-00aa00573819");
    internal static Guid guidTableDesignContext = new Guid("4194fee5-6777-419f-a5fc-47a536df1bdb");
    internal static Guid guidViewDesignContext = new Guid("b968e165-98e0-41f0-8fbe-a8ed1d246a90");

    public SQLiteCommandHandler()
    {
    }

    public override OleCommandStatus GetCommandStatus(int[] itemIds, OleCommand command, OleCommandTextType textType, OleCommandStatus status)
    {
................................................................................
      Microsoft.VisualStudio.OLE.Interop.IServiceProvider provider = DataViewHierarchyAccessor.ServiceProvider as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
      IVsUIShell shell = DataViewHierarchyAccessor.ServiceProvider.GetService(typeof(IVsUIShell)) as IVsUIShell;
      IVsUIHierarchy hier = DataViewHierarchyAccessor.Hierarchy;
      IVsWindowFrame frame;

      if (shell != null)
      {
        TableDesignerDoc form = new TableDesignerDoc(itemId, DataViewHierarchyAccessor, tableName);
        IntPtr formptr = System.Runtime.InteropServices.Marshal.GetIUnknownForObject(form);
        Guid empty = Guid.Empty;
        FakeHierarchy fake = new FakeHierarchy(form, hier);

        int code = shell.CreateDocumentWindow(
          0, // (uint)(__VSCREATEDOCWIN.CDW_fCreateNewWindow | __VSCREATEDOCWIN.CDW_RDTFLAGS_MASK) | (uint)(_VSRDTFLAGS.RDT_CanBuildFromMemory | _VSRDTFLAGS.RDT_NonCreatable | _VSRDTFLAGS.RDT_VirtualDocument | _VSRDTFLAGS.RDT_DontAddToMRU),
          form.Name, fake, (uint)itemId, formptr, formptr, ref empty, null, ref guidTableDesignContext, provider, "", form.Caption, null, out frame);

        if (frame != null)
        {
          object ret;
          int prop = (int)__VSFPROPID.VSFPROPID_Caption;
          
          code = frame.GetProperty(prop, out ret);
................................................................................
      Microsoft.VisualStudio.OLE.Interop.IServiceProvider provider = DataViewHierarchyAccessor.ServiceProvider as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
      IVsUIShell shell = DataViewHierarchyAccessor.ServiceProvider.GetService(typeof(IVsUIShell)) as IVsUIShell;
      IVsUIHierarchy hier = DataViewHierarchyAccessor.Hierarchy;
      IVsWindowFrame frame;

      if (shell != null)
      {
        ViewDesignerDoc form = new ViewDesignerDoc(itemId, DataViewHierarchyAccessor, viewName);
        IntPtr formptr = System.Runtime.InteropServices.Marshal.GetIUnknownForObject(form);
        Guid empty = Guid.Empty;
        FakeHierarchy fake = new FakeHierarchy(form, hier);

        int code = shell.CreateDocumentWindow(
          0, // (uint)(__VSCREATEDOCWIN.CDW_fCreateNewWindow | __VSCREATEDOCWIN.CDW_RDTFLAGS_MASK) | (uint)(_VSRDTFLAGS.RDT_CanBuildFromMemory | _VSRDTFLAGS.RDT_NonCreatable | _VSRDTFLAGS.RDT_VirtualDocument | _VSRDTFLAGS.RDT_DontAddToMRU),
          form.Name, fake, (uint)itemId, formptr, formptr, ref empty, null, ref guidViewDesignContext, provider, "", form.Caption, null, out frame);

        if (frame != null)
        {
          object ret;
          int prop = (int)__VSFPROPID.VSFPROPID_Caption;

          code = frame.GetProperty(prop, out ret);
................................................................................

            Refresh(itemId);
          }
        }
      }
    }

    public void Refresh(int itemId)
    {
      Refresh(DataViewHierarchyAccessor, itemId);
    }

    public static void Refresh(DataViewHierarchyAccessor accessor, int itemId)
    {
      IVsUIHierarchy hier = accessor.Hierarchy as IVsUIHierarchy;
      Guid g = VSConstants.GUID_VSStandardCommandSet97;
      hier.ExecCommand((uint)itemId, ref g, (uint)0xbd, (uint)OleCommandExecutionOption.DoDefault, IntPtr.Zero, IntPtr.Zero);
    }
  }
}

Changes to SQLite.Designer/SQLiteDataObjectIdentifierResolver.cs.

52
53
54
55
56
57
58

59
60
61
62
63
64
65
        case "view":
          length = 3;
          break;
        case "column":
        case "index":
        case "foreignkey":
        case "viewcolumn":

          length = 4;
          break;
        case "indexcolumn":
        case "foreignkeycolumn":
          length = 5;
          break;
        default:







>







52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
        case "view":
          length = 3;
          break;
        case "column":
        case "index":
        case "foreignkey":
        case "viewcolumn":
        case "triggers":
          length = 4;
          break;
        case "indexcolumn":
        case "foreignkeycolumn":
          length = 5;
          break;
        default:

Changes to SQLite.Designer/SQLiteDataObjectSupport.xml.

275
276
277
278
279
280
281

282
283
284
285
286
287
288
...
512
513
514
515
516
517
518




































519
520
521
522
523
524
525
				<Property name="Name" type="System.String" itemName="column_name"/>
				<Property name="Ordinal" type="System.Int32" itemName="ordinal_position">
					<Concepts>
						<Concept name="Ordinal">
						</Concept>
					</Concepts>
				</Property>

        <Property name="SystemType" type="System.String" itemName="data_type">
          <Concepts>
            <Concept name="UserDataType"/>
            <Concept name="NativeDataType"/>
            <Concept name="ProviderDataType">
              <Conversion mapper="Microsoft.VisualStudio.Data.AdoDotNet.AdoDotNetObjectConceptMapper"/>
            </Concept>
................................................................................
              </Parameter>
            </Parameter>
          </Parameter>
        </Action>
      </Actions>
    </Type>





































    <Type name="ForeignKey" defaultSort="Database,Table,Name">
      <Concepts>
        <Concept name="TableForeignKey" restrictions="{Catalog},null,{Table},{Name}"/>
      </Concepts>
      <Identifier>
        <Part name="Database" itemName="table_catalog">
          <Concepts>







>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
...
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
				<Property name="Name" type="System.String" itemName="column_name"/>
				<Property name="Ordinal" type="System.Int32" itemName="ordinal_position">
					<Concepts>
						<Concept name="Ordinal">
						</Concept>
					</Concepts>
				</Property>
        <Property name="DataType" type="System.String" itemName="data_type" />
        <Property name="SystemType" type="System.String" itemName="data_type">
          <Concepts>
            <Concept name="UserDataType"/>
            <Concept name="NativeDataType"/>
            <Concept name="ProviderDataType">
              <Conversion mapper="Microsoft.VisualStudio.Data.AdoDotNet.AdoDotNetObjectConceptMapper"/>
            </Concept>
................................................................................
              </Parameter>
            </Parameter>
          </Parameter>
        </Action>
      </Actions>
    </Type>

    <Type name="Triggers" defaultSort="Database,Table,Name">
      <Concepts>
        <Concept name="TableTriggers" restrictions="{Catalog},null,{Table},{Name}"/>
      </Concepts>
      <Identifier>
        <Part name="Database" itemName="table_catalog">
          <Concepts>
            <Concept name="Identifier0"/>
          </Concepts>
        </Part>
        <Part name="Schema" itemName="table_schema">
          <Concepts>
            <Concept name="Identifier1"/>
          </Concepts>
        </Part>
        <Part name="Table" itemName="table_name">
          <Concepts>
            <Concept name="Identifier2"/>
          </Concepts>
        </Part>
        <Part name="Name" itemName="trigger_name">
          <Concepts>
            <Concept name="Identifier3"/>
          </Concepts>
        </Part>
      </Identifier>
      <Properties>
        <Property name="Name" type="System.String" itemName="trigger_name"/>
      </Properties>
      <Actions>
        <Action name="Enumerate" guid="61CC0372-384D-42e5-9707-6D7C8DC5287A" handler="Microsoft.VisualStudio.Data.AdoDotNet.AdoDotNetObjectEnumerator">
          <Parameter value="Triggers"/>
        </Action>
      </Actions>
    </Type>
    
    <Type name="ForeignKey" defaultSort="Database,Table,Name">
      <Concepts>
        <Concept name="TableForeignKey" restrictions="{Catalog},null,{Table},{Name}"/>
      </Concepts>
      <Identifier>
        <Part name="Database" itemName="table_catalog">
          <Concepts>

Changes to SQLite.Designer/SQLiteDataViewSupport2005.xml.

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
...
133
134
135
136
137
138
139
140




































141
142
143
144
145
146
147
...
197
198
199
200
201
202
203

204
205
206
207
208
209
210
211

212
213
214
215
216
217
218
...
248
249
250
251
252
253
254















255
256
257
258
259
260
261
            </CommandBindings>
						<Children>
							<Selection type="View">
								<SelectionNode nid="View">
                  <DisplayName>{View.Name}</DisplayName>
                  <Icon name="View"/>
									<Children>
										<Selection type="ViewColumn" restrictions="{View.Database},null,{View.Name}">
											<SelectionNode>
												<Icon name="Column"/>
											</SelectionNode>
										</Selection>
									</Children>
								</SelectionNode>
							</Selection>
						</Children>
					</StaticNode>                    

				</Children>
			</StaticConnectionNode>
		</DataView>
	</DataViews>
  <SubHierarchies>
    <SubHierarchy name="table children">      
      <StaticNode nid="Columns">
        <DisplayName>Columns</DisplayName>
................................................................................
          <Selection type="ForeignKey" restrictions="{Table.Database},null,{Table.Name}">
            <SelectionNode>
              <Icon name="ForeignKey"/>
            </SelectionNode>
          </Selection>
        </Children>
      </StaticNode>
      




































    </SubHierarchy>
  </SubHierarchies>
  <TypeExtensions>
    
    <TypeExtension name="Table">
      <Identifier>
        <Part name="Name">
................................................................................
    
    <TypeExtension name="ViewColumn">
      <Identifier>
        <Part name="Name">
          <Category resource="Category_Identity"/>
        </Part>
        <Part name="Database">

          <Category resource="Category_Location"/>
        </Part>
        <Part name="View">
          <Category resource="Category_Location"/>
        </Part>
      </Identifier>
      <Properties>
        <Property name="Ordinal"/>

        <Property name="DataType">
          <DisplayName>Data Type</DisplayName>
        </Property>
        <Property name="Nullable">
          <DisplayName>Allow Nulls</DisplayName>
        </Property>
        <Property name="Default">
................................................................................
      <CommandBindings>
        <CommandBinding name="NewQuery" guid="501822E1-B5AF-11d0-B4DC-00A0C91506EF" cmdid="13608" handler="884DD964-5327-461f-9F06-6484DD540F8F"/>
        <CommandBinding name="DropIndex" guid="5efc7975-14bc-11cf-9b2b-00aa00573819" cmdid="17" handler="SQLite.Designer.SQLiteCommandHandler">
          <Parameter value="Index"/>
        </CommandBinding>
      </CommandBindings>
    </TypeExtension>
















    <TypeExtension name="TableColumn">
      <Identifier>
        <Part name="Name">
          <Category resource="Category_Identity"/>
        </Part>
        <Part name="Database">







|
<
<
<
<




|
>
|







 







|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>








>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







69
70
71
72
73
74
75
76




77
78
79
80
81
82
83
84
85
86
87
88
89
90
...
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
...
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
...
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
            </CommandBindings>
						<Children>
							<Selection type="View">
								<SelectionNode nid="View">
                  <DisplayName>{View.Name}</DisplayName>
                  <Icon name="View"/>
									<Children>
                    <SubHierarchyRef name="View children"/>




									</Children>
								</SelectionNode>
							</Selection>
						</Children>
					</StaticNode>
                  
        </Children>
			</StaticConnectionNode>
		</DataView>
	</DataViews>
  <SubHierarchies>
    <SubHierarchy name="table children">      
      <StaticNode nid="Columns">
        <DisplayName>Columns</DisplayName>
................................................................................
          <Selection type="ForeignKey" restrictions="{Table.Database},null,{Table.Name}">
            <SelectionNode>
              <Icon name="ForeignKey"/>
            </SelectionNode>
          </Selection>
        </Children>
      </StaticNode>

      <StaticNode nid="Triggers">
        <DisplayName>Triggers</DisplayName>
        <Children>
          <Selection type="Triggers" restrictions="{Table.Database},null,{Table.Name}">
            <SelectionNode>
              <Icon name="Index" />
            </SelectionNode>
          </Selection>
        </Children>
      </StaticNode>
    </SubHierarchy>
    <SubHierarchy name="view children">      
      <StaticNode nid="Columns">
        <DisplayName>Columns</DisplayName>
        <CommandBindings>
          <CommandBinding name="NewQuery" guid="501822E1-B5AF-11d0-B4DC-00A0C91506EF" cmdid="13608" handler="884DD964-5327-461f-9F06-6484DD540F8F"/>
        </CommandBindings>
        <Children>
          <Selection type="ViewColumn" restrictions="{View.Database},null,{View.Name}">
            <SelectionNode>
              <Icon name="Column"/>
            </SelectionNode>
          </Selection>
        </Children>
      </StaticNode>
      
      <StaticNode nid="Triggers">
        <DisplayName>Triggers</DisplayName>
        <Children>
          <Selection type="Triggers" restrictions="{View.Database},null,{View.Name}">
            <SelectionNode>
              <Icon name="Index" />
            </SelectionNode>
          </Selection>
        </Children>
      </StaticNode>
    </SubHierarchy>
  </SubHierarchies>
  <TypeExtensions>
    
    <TypeExtension name="Table">
      <Identifier>
        <Part name="Name">
................................................................................
    
    <TypeExtension name="ViewColumn">
      <Identifier>
        <Part name="Name">
          <Category resource="Category_Identity"/>
        </Part>
        <Part name="Database">
          <DisplayName>Catalog</DisplayName>
          <Category resource="Category_Location"/>
        </Part>
        <Part name="View">
          <Category resource="Category_Location"/>
        </Part>
      </Identifier>
      <Properties>
        <Property name="Ordinal"/>
        <Property name="Length"/>
        <Property name="DataType">
          <DisplayName>Data Type</DisplayName>
        </Property>
        <Property name="Nullable">
          <DisplayName>Allow Nulls</DisplayName>
        </Property>
        <Property name="Default">
................................................................................
      <CommandBindings>
        <CommandBinding name="NewQuery" guid="501822E1-B5AF-11d0-B4DC-00A0C91506EF" cmdid="13608" handler="884DD964-5327-461f-9F06-6484DD540F8F"/>
        <CommandBinding name="DropIndex" guid="5efc7975-14bc-11cf-9b2b-00aa00573819" cmdid="17" handler="SQLite.Designer.SQLiteCommandHandler">
          <Parameter value="Index"/>
        </CommandBinding>
      </CommandBindings>
    </TypeExtension>

    <TypeExtension name="Triggers">
      <Identifier>
        <Part name="Name">
          <Category resource="Category_Identity"/>
        </Part>
        <Part name="Database">
          <DisplayName>Catalog</DisplayName>
          <Category resource="Category_Location"/>
        </Part>
        <Part name="Table">
          <Category resource="Category_Location"/>
        </Part>
      </Identifier>
    </TypeExtension>

    <TypeExtension name="TableColumn">
      <Identifier>
        <Part name="Name">
          <Category resource="Category_Identity"/>
        </Part>
        <Part name="Database">

Changes to SQLite.Designer/SQLiteDataViewSupport2008.xml.

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
...
133
134
135
136
137
138
139
140










141




























142
143
144
145
146
147
148
...
197
198
199
200
201
202
203

204
205
206
207
208
209
210
211

212
213
214
215
216
217
218
...
248
249
250
251
252
253
254















255
256
257
258
259
260
261
            </CommandBindings>
						<Children>
							<Selection type="View">
								<SelectionNode nid="View">
                  <DisplayName>{View.Name}</DisplayName>
                  <Icon name="View"/>
									<Children>
										<Selection type="ViewColumn" restrictions="{View.Database},null,{View.Name}">
											<SelectionNode>
												<Icon name="Column"/>
											</SelectionNode>
										</Selection>
									</Children>
								</SelectionNode>
							</Selection>
						</Children>
					</StaticNode>                    

				</Children>
			</StaticConnectionNode>
		</DataView>
	</DataViews>

  <SubHierarchies>
    <SubHierarchy name="table children">      
      <StaticNode nid="Columns">
        <DisplayName>Columns</DisplayName>
        <CommandBindings>
          <CommandBinding name="NewQuery" guid="501822E1-B5AF-11d0-B4DC-00A0C91506EF" cmdid="13608" handler="884DD964-5327-461f-9F06-6484DD540F8F"/>
        </CommandBindings>
................................................................................
          <Selection type="ForeignKey" restrictions="{Table.Database},null,{Table.Name}">
            <SelectionNode>
              <Icon name="ForeignKey"/>
            </SelectionNode>
          </Selection>
        </Children>
      </StaticNode>
      










    </SubHierarchy>




























  </SubHierarchies>
  <TypeExtensions>
    
    <TypeExtension name="Table">
      <Identifier>
        <Part name="Name">
          <Category resource="Category_Identity"/>
................................................................................
    
    <TypeExtension name="ViewColumn">
      <Identifier>
        <Part name="Name">
          <Category resource="Category_Identity"/>
        </Part>
        <Part name="Database">

          <Category resource="Category_Location"/>
        </Part>
        <Part name="View">
          <Category resource="Category_Location"/>
        </Part>
      </Identifier>
      <Properties>
        <Property name="Ordinal"/>

        <Property name="DataType">
          <DisplayName>Data Type</DisplayName>
        </Property>
        <Property name="Nullable">
          <DisplayName>Allow Nulls</DisplayName>
        </Property>
        <Property name="Default">
................................................................................
      <CommandBindings>
        <CommandBinding name="NewQuery" guid="501822E1-B5AF-11d0-B4DC-00A0C91506EF" cmdid="13608" handler="884DD964-5327-461f-9F06-6484DD540F8F"/>
        <CommandBinding name="DropIndex" guid="5efc7975-14bc-11cf-9b2b-00aa00573819" cmdid="17" handler="SQLite.Designer.SQLiteCommandHandler">
          <Parameter value="Index"/>
        </CommandBinding>
      </CommandBindings>
    </TypeExtension>
















    <TypeExtension name="TableColumn">
      <Identifier>
        <Part name="Name">
          <Category resource="Category_Identity"/>
        </Part>
        <Part name="Database">







|
<
<
<
<




|
>




>







 







|
>
>
>
>
>
>
>
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>








>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
...
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
...
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
...
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
            </CommandBindings>
						<Children>
							<Selection type="View">
								<SelectionNode nid="View">
                  <DisplayName>{View.Name}</DisplayName>
                  <Icon name="View"/>
									<Children>
                    <SubHierarchyRef name="View children"/>




									</Children>
								</SelectionNode>
							</Selection>
						</Children>
					</StaticNode>   
          
				</Children>
			</StaticConnectionNode>
		</DataView>
	</DataViews>
  
  <SubHierarchies>
    <SubHierarchy name="table children">      
      <StaticNode nid="Columns">
        <DisplayName>Columns</DisplayName>
        <CommandBindings>
          <CommandBinding name="NewQuery" guid="501822E1-B5AF-11d0-B4DC-00A0C91506EF" cmdid="13608" handler="884DD964-5327-461f-9F06-6484DD540F8F"/>
        </CommandBindings>
................................................................................
          <Selection type="ForeignKey" restrictions="{Table.Database},null,{Table.Name}">
            <SelectionNode>
              <Icon name="ForeignKey"/>
            </SelectionNode>
          </Selection>
        </Children>
      </StaticNode>

      <StaticNode nid="Triggers">
        <DisplayName>Triggers</DisplayName>
        <Children>
          <Selection type="Triggers" restrictions="{Table.Database},null,{Table.Name}">
            <SelectionNode>
              <Icon name="Index" />
            </SelectionNode>
          </Selection>
        </Children>
      </StaticNode>
    </SubHierarchy>
    
    <SubHierarchy name="view children">      
      <StaticNode nid="Columns">
        <DisplayName>Columns</DisplayName>
        <CommandBindings>
          <CommandBinding name="NewQuery" guid="501822E1-B5AF-11d0-B4DC-00A0C91506EF" cmdid="13608" handler="884DD964-5327-461f-9F06-6484DD540F8F"/>
        </CommandBindings>
        <Children>
          <Selection type="ViewColumn" restrictions="{View.Database},null,{View.Name}">
            <SelectionNode>
              <Icon name="Column"/>
            </SelectionNode>
          </Selection>
        </Children>
      </StaticNode>
      
      <StaticNode nid="Triggers">
        <DisplayName>Triggers</DisplayName>
        <Children>
          <Selection type="Triggers" restrictions="{View.Database},null,{View.Name}">
            <SelectionNode>
              <Icon name="Index" />
            </SelectionNode>
          </Selection>
        </Children>
      </StaticNode>
    </SubHierarchy>
    
  </SubHierarchies>
  <TypeExtensions>
    
    <TypeExtension name="Table">
      <Identifier>
        <Part name="Name">
          <Category resource="Category_Identity"/>
................................................................................
    
    <TypeExtension name="ViewColumn">
      <Identifier>
        <Part name="Name">
          <Category resource="Category_Identity"/>
        </Part>
        <Part name="Database">
          <DisplayName>Catalog</DisplayName>
          <Category resource="Category_Location"/>
        </Part>
        <Part name="View">
          <Category resource="Category_Location"/>
        </Part>
      </Identifier>
      <Properties>
        <Property name="Ordinal"/>
        <Property name="Length"/>
        <Property name="DataType">
          <DisplayName>Data Type</DisplayName>
        </Property>
        <Property name="Nullable">
          <DisplayName>Allow Nulls</DisplayName>
        </Property>
        <Property name="Default">
................................................................................
      <CommandBindings>
        <CommandBinding name="NewQuery" guid="501822E1-B5AF-11d0-B4DC-00A0C91506EF" cmdid="13608" handler="884DD964-5327-461f-9F06-6484DD540F8F"/>
        <CommandBinding name="DropIndex" guid="5efc7975-14bc-11cf-9b2b-00aa00573819" cmdid="17" handler="SQLite.Designer.SQLiteCommandHandler">
          <Parameter value="Index"/>
        </CommandBinding>
      </CommandBindings>
    </TypeExtension>

    <TypeExtension name="Triggers">
      <Identifier>
        <Part name="Name">
          <Category resource="Category_Identity"/>
        </Part>
        <Part name="Database">
          <DisplayName>Catalog</DisplayName>
          <Category resource="Category_Location"/>
        </Part>
        <Part name="Table">
          <Category resource="Category_Location"/>
        </Part>
      </Identifier>
    </TypeExtension>

    <TypeExtension name="TableColumn">
      <Identifier>
        <Part name="Name">
          <Category resource="Category_Identity"/>
        </Part>
        <Part name="Database">

Changes to SQLite.Designer/TableNameDialog.Designer.cs.

84
85
86
87
88
89
90

91
92
93
94
95
96
97
      this.Controls.Add(this.label1);
      this.Controls.Add(_cancel);
      this.Controls.Add(_ok);
      this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
      this.MaximizeBox = false;
      this.MinimizeBox = false;
      this.Name = "TableNameDialog";

      this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
      this.Text = "% Name";
      this.ResumeLayout(false);
      this.PerformLayout();

    }








>







84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
      this.Controls.Add(this.label1);
      this.Controls.Add(_cancel);
      this.Controls.Add(_ok);
      this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
      this.MaximizeBox = false;
      this.MinimizeBox = false;
      this.Name = "TableNameDialog";
      this.Font = new System.Drawing.Font("MS Shell Dlg 2", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
      this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
      this.Text = "% Name";
      this.ResumeLayout(false);
      this.PerformLayout();

    }

Changes to SQLite.Designer/TableNameDialog.cs.

1
2
3
4
5
6
7
8
9
10








11
12
13
14
15
16
17
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace SQLite.Designer
{








  public partial class TableNameDialog : Form
  {
    public TableNameDialog()
      : this("Table", null)
    {
    }

|
|
|
|
|
|
<



>
>
>
>
>
>
>
>







1
2
3
4
5
6

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/********************************************************
 * ADO.NET 2.0 Data Provider for SQLite Version 3.X
 * Written by Robert Simpson (robert@blackcastlesoft.com)
 * 
 * Released to the public domain, use at your own risk!
 ********************************************************/


namespace SQLite.Designer
{
  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Text;
  using System.Windows.Forms;

  public partial class TableNameDialog : Form
  {
    public TableNameDialog()
      : this("Table", null)
    {
    }

Changes to SQLite.Designer/VSPackage.Designer.cs.

1
2
3
4
5
6
7
8
9
10
11
..
82
83
84
85
86
87
88







89
90
91
92
93
94
95
96
97
98
99
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.1433
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace SQLite.Designer {
................................................................................
        ///   Looks up a localized string similar to The database and its metadata will be encrypted using the supplied password as a hash..
        /// </summary>
        internal static string Encrypt {
            get {
                return ResourceManager.GetString("Encrypt", resourceCulture);
            }
        }







        
        /// <summary>
        ///   Looks up a localized string similar to The database and its metadata will be re-encrypted using the supplied password as a hash..
        /// </summary>
        internal static string ReEncrypt {
            get {
                return ResourceManager.GetString("ReEncrypt", resourceCulture);
            }
        }
    }
}



|







 







>
>
>
>
>
>
>











1
2
3
4
5
6
7
8
9
10
11
..
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
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.3031
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace SQLite.Designer {
................................................................................
        ///   Looks up a localized string similar to The database and its metadata will be encrypted using the supplied password as a hash..
        /// </summary>
        internal static string Encrypt {
            get {
                return ResourceManager.GetString("Encrypt", resourceCulture);
            }
        }
        
        internal static System.Drawing.Bitmap info {
            get {
                object obj = ResourceManager.GetObject("info", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }
        
        /// <summary>
        ///   Looks up a localized string similar to The database and its metadata will be re-encrypted using the supplied password as a hash..
        /// </summary>
        internal static string ReEncrypt {
            get {
                return ResourceManager.GetString("ReEncrypt", resourceCulture);
            }
        }
    }
}

Changes to SQLite.Designer/VSPackage.resx.

113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131







132
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <data name="400" xml:space="preserve">
    <value>MHM2ZQETQKDTJEPTC1MTQCZ1R1KQEMAPZHETDZPZI9RPJ0E0DHAHKCHZPKQ8AQZICADHKIZ1JAQED8IDEHZPZKZEIKAQERHPRCQMAMRKDEZZQRDRDHJEZIKECZPDIIKC</value>
  </data>
  <data name="Decrypt" xml:space="preserve">
    <value>The database and its metadata will be un-encrypted.  No password will be required to open the database and view its contents.</value>
  </data>
  <data name="Encrypt" xml:space="preserve">
    <value>The database and its metadata will be encrypted using the supplied password as a hash.</value>
  </data>
  <data name="ReEncrypt" xml:space="preserve">
    <value>The database and its metadata will be re-encrypted using the supplied password as a hash.</value>
  </data>







</root>







<
<
<









>
>
>
>
>
>
>

113
114
115
116
117
118
119



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>



  <data name="Decrypt" xml:space="preserve">
    <value>The database and its metadata will be un-encrypted.  No password will be required to open the database and view its contents.</value>
  </data>
  <data name="Encrypt" xml:space="preserve">
    <value>The database and its metadata will be encrypted using the supplied password as a hash.</value>
  </data>
  <data name="ReEncrypt" xml:space="preserve">
    <value>The database and its metadata will be re-encrypted using the supplied password as a hash.</value>
  </data>
  <data name="400" xml:space="preserve">
    <value>MHM2ZQETQKDTJEPTC1MTQCZ1R1KQEMAPZHETDZPZI9RPJ0E0DHAHKCHZPKQ8AQZICADHKIZ1JAQED8IDEHZPZKZEIKAQERHPRCQMAMRKDEZZQRDRDHJEZIKECZPDIIKC</value>
  </data>
  <assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  <data name="info" type="System.Resources.ResXFileRef, System.Windows.Forms">
    <value>Resources\info.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
  </data>
</root>

Changes to SQLite.Interop/SQLite.Interop.rc.

49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
..
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

/////////////////////////////////////////////////////////////////////////////
//
// Version
//

VS_VERSION_INFO VERSIONINFO
 FILEVERSION 1,0,52,0
 PRODUCTVERSION 1,0,0,0
 FILEFLAGSMASK 0x17L
#ifdef _DEBUG
 FILEFLAGS 0x1L
#else
 FILEFLAGS 0x0L
#endif
................................................................................
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904b0"
        BEGIN
            VALUE "Comments", "http://sqlite.phxsoftware.com"
            VALUE "FileDescription", "System.Data.SQLite Interop Library"
            VALUE "FileVersion", "1.0.52.0"
            VALUE "InternalName", "SQLite.Interop.DLL"
            VALUE "LegalCopyright", "Released to the public domain"
            VALUE "OriginalFilename", "SQLite3.DLL 3.6.0"
            VALUE "ProductName", "System.Data.SQLite"
            VALUE "ProductVersion", "1.0"
        END
    END







|







 







|







49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
..
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

/////////////////////////////////////////////////////////////////////////////
//
// Version
//

VS_VERSION_INFO VERSIONINFO
 FILEVERSION 1,0,53,0
 PRODUCTVERSION 1,0,0,0
 FILEFLAGSMASK 0x17L
#ifdef _DEBUG
 FILEFLAGS 0x1L
#else
 FILEFLAGS 0x0L
#endif
................................................................................
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904b0"
        BEGIN
            VALUE "Comments", "http://sqlite.phxsoftware.com"
            VALUE "FileDescription", "System.Data.SQLite Interop Library"
            VALUE "FileVersion", "1.0.53.0"
            VALUE "InternalName", "SQLite.Interop.DLL"
            VALUE "LegalCopyright", "Released to the public domain"
            VALUE "OriginalFilename", "SQLite3.DLL 3.6.0"
            VALUE "ProductName", "System.Data.SQLite"
            VALUE "ProductVersion", "1.0"
        END
    END

Changes to SQLite.Interop/interop.c.

305
306
307
308
309
310
311

312
313
314
315
316
317

318
319
320
321
322
323
324
{
  sqlite3_free(z);
}

__declspec(dllexport) int WINAPI sqlite3_open_interop(const char*filename, sqlite3 **ppdb)
{
  int ret = sqlite3_open(filename, ppdb);

  return ret;
}

__declspec(dllexport) int WINAPI sqlite3_open16_interop(const void *filename, sqlite3 **ppdb)
{
  int ret = sqlite3_open16(filename, ppdb);

  return ret;
}

__declspec(dllexport) int WINAPI sqlite3_errcode_interop(sqlite3 *db)
{
  return sqlite3_errcode(db);
}







>






>







305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
{
  sqlite3_free(z);
}

__declspec(dllexport) int WINAPI sqlite3_open_interop(const char*filename, sqlite3 **ppdb)
{
  int ret = sqlite3_open(filename, ppdb);
  if (!ret) sqlite3_enable_load_extension(*ppdb, 1);
  return ret;
}

__declspec(dllexport) int WINAPI sqlite3_open16_interop(const void *filename, sqlite3 **ppdb)
{
  int ret = sqlite3_open16(filename, ppdb);
  if (!ret) sqlite3_enable_load_extension(*ppdb, 1);
  return ret;
}

__declspec(dllexport) int WINAPI sqlite3_errcode_interop(sqlite3 *db)
{
  return sqlite3_errcode(db);
}

Changes to SQLite.Interop/merge.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// This code was automatically generated from assembly
// C:\Src\SQLite.NET\System.Data.SQLite\bin\CompactFramework\System.Data.SQLite.dll

#include <windef.h>

#pragma data_seg(push,clrseg,".clr")
#pragma comment(linker, "/SECTION:.clr,ER")
  char __ph[137456] = {0}; // The number of bytes to reserve
#pragma data_seg(pop,clrseg)

typedef BOOL (WINAPI *DLLMAIN)(HANDLE, DWORD, LPVOID);
typedef struct EXTRA_STUFF
{
  DWORD dwNativeEntryPoint;
} EXTRA_STUFF, *LPEXTRA_STUFF;







|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// This code was automatically generated from assembly
// C:\Src\SQLite.NET\System.Data.SQLite\bin\CompactFramework\System.Data.SQLite.dll

#include <windef.h>

#pragma data_seg(push,clrseg,".clr")
#pragma comment(linker, "/SECTION:.clr,ER")
  char __ph[138636] = {0}; // The number of bytes to reserve
#pragma data_seg(pop,clrseg)

typedef BOOL (WINAPI *DLLMAIN)(HANDLE, DWORD, LPVOID);
typedef struct EXTRA_STUFF
{
  DWORD dwNativeEntryPoint;
} EXTRA_STUFF, *LPEXTRA_STUFF;

Changes to SQLite.Interop/merge_full.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// This code was automatically generated from assembly
// C:\Src\SQLite.NET\System.Data.SQLite\bin\System.Data.SQLite.dll

#include <windef.h>

#pragma data_seg(push,clrseg,".clr")
#pragma comment(linker, "/SECTION:.clr,ER")
  char __ph[149816] = {0}; // The number of bytes to reserve
#pragma data_seg(pop,clrseg)

typedef BOOL (WINAPI *DLLMAIN)(HANDLE, DWORD, LPVOID);
typedef struct EXTRA_STUFF
{
  DWORD dwNativeEntryPoint;
} EXTRA_STUFF, *LPEXTRA_STUFF;







|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// This code was automatically generated from assembly
// C:\Src\SQLite.NET\System.Data.SQLite\bin\System.Data.SQLite.dll

#include <windef.h>

#pragma data_seg(push,clrseg,".clr")
#pragma comment(linker, "/SECTION:.clr,ER")
  char __ph[151004] = {0}; // The number of bytes to reserve
#pragma data_seg(pop,clrseg)

typedef BOOL (WINAPI *DLLMAIN)(HANDLE, DWORD, LPVOID);
typedef struct EXTRA_STUFF
{
  DWORD dwNativeEntryPoint;
} EXTRA_STUFF, *LPEXTRA_STUFF;

Changes to SQLite.NET.suo.

cannot compute difference between binary files

Changes to System.Data.SQLite.Linq/SQL.

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
//---------------------------------------------------------------------
// <copyright file="TopClause.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//---------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;

using System.Data.Metadata.Edm;
using System.Data.Common.CommandTrees;



namespace System.Data.SQLite
{
  /// <summary>
  /// TopClause represents the a TOP expression in a SqlSelectStatement. 
  /// It has a count property, which indicates how many TOP rows should be selected and a 
  /// boolen WithTies property.























































































































































































  /// </summary>




















































































































































































































































































  class TopClause : ISqlFragment

  {























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































    ISqlFragment topCount;
    bool withTies;

















    /// <summary>
    /// Do we need to add a WITH_TIES to the top statement


    /// </summary>
    internal bool WithTies



    {


































      get { return withTies; }

















































































































































































































































    }

    /// <summary>
    /// How many top rows should be selected.
    /// </summary>
    internal ISqlFragment TopCount


    {
      get { return topCount; }













































    }

    /// <summary>
    /// Creates a TopClause with the given topCount and withTies.



    /// </summary>
    /// <param name="topCount"></param>
    /// <param name="withTies"></param>
    internal TopClause(ISqlFragment topCount, bool withTies)


    {
      this.topCount = topCount;
      this.withTies = withTies;









    }

    /// <summary>
    /// Creates a TopClause with the given topCount and withTies.

    /// </summary>
    /// <param name="topCount"></param>
    /// <param name="withTies"></param>
    internal TopClause(int topCount, bool withTies)

    {
      SqlBuilder sqlBuilder = new SqlBuilder();
      sqlBuilder.Append(topCount.ToString(CultureInfo.InvariantCulture));
      this.topCount = sqlBuilder;
      this.withTies = withTies;
    }

    #region ISqlFragment Members


    /// <summary>
    /// Write out the TOP part of sql select statement 
    /// It basically writes TOP (X) [WITH TIES].
    /// </summary>
    /// <param name="writer"></param>
    /// <param name="sqlGenerator"></param>
    public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator)


    {
      writer.Write("LIMIT ");
      this.TopCount.WriteSql(writer, sqlGenerator);


      if (this.WithTies)
        throw new NotSupportedException("WITH TIES");


      //writer.Write(" ");

      //if (this.WithTies)
      //{
      //    writer.Write("WITH TIES ");
      //}

    }

    #endregion
  }
}

|










>


>
>




|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
<

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

<
>
>

<
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



|

|
>
>

<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



|
>
>
>

|
<
<
>
>

<
<
>
>
>
>
>
>
>
>
>



|
>

|
<
|
>

<
|
|
<
<
|
<
>
|
<
<
<
<
<
<
<
>
>
|
<
<
>
|
<
<
>
|
<

<
<
<
<
>
|

<
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391

3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409

3410
3411
3412

3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701

3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755


3756
3757
3758


3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774

3775
3776
3777

3778
3779


3780

3781
3782







3783
3784
3785


3786
3787


3788
3789

3790




3791
3792
3793

3794
3795
//---------------------------------------------------------------------
// <copyright file="SqlGenerator.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//---------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Data.Common;
using System.Data.Metadata.Edm;
using System.Data.Common.CommandTrees;
using System.Data;


namespace System.Data.SQLite
{
  /// <summary>
  /// Translates the command object into a SQL string that can be executed on
  /// SQL Server 2005.
  /// </summary>
  /// <remarks>
  /// The translation is implemented as a visitor <see cref="DbExpressionVisitor{T}"/>
  /// over the query tree.  It makes a single pass over the tree, collecting the sql
  /// fragments for the various nodes in the tree <see cref="ISqlFragment"/>.
  ///
  /// The major operations are
  /// <list type="bullet">
  /// <item>Select statement minimization.  Multiple nodes in the query tree
  /// that can be part of a single SQL select statement are merged. e.g. a
  /// Filter node that is the input of a Project node can typically share the
  /// same SQL statement.</item>
  /// <item>Alpha-renaming.  As a result of the statement minimization above, there
  /// could be name collisions when using correlated subqueries
  /// <example>
  /// <code>
  /// Filter(
  ///     b = Project( c.x
  ///         c = Extent(foo)
  ///         )
  ///     exists (
  ///         Filter(
  ///             c = Extent(foo)
  ///             b.x = c.x
  ///             )
  ///     )
  /// )
  /// </code>
  /// The first Filter, Project and Extent will share the same SQL select statement.
  /// The alias for the Project i.e. b, will be replaced with c.
  /// If the alias c for the Filter within the exists clause is not renamed,
  /// we will get <c>c.x = c.x</c>, which is incorrect.
  /// Instead, the alias c within the second filter should be renamed to c1, to give
  /// <c>c.x = c1.x</c> i.e. b is renamed to c, and c is renamed to c1.
  /// </example>
  /// </item>
  /// <item>Join flattening.  In the query tree, a list of join nodes is typically
  /// represented as a tree of Join nodes, each with 2 children. e.g.
  /// <example>
  /// <code>
  /// a = Join(InnerJoin
  ///     b = Join(CrossJoin
  ///         c = Extent(foo)
  ///         d = Extent(foo)
  ///         )
  ///     e = Extent(foo)
  ///     on b.c.x = e.x
  ///     )
  /// </code>
  /// If translated directly, this will be translated to
  /// <code>
  /// FROM ( SELECT c.*, d.*
  ///         FROM foo as c
  ///         CROSS JOIN foo as d) as b
  /// INNER JOIN foo as e on b.x' = e.x
  /// </code>
  /// It would be better to translate this as
  /// <code>
  /// FROM foo as c
  /// CROSS JOIN foo as d
  /// INNER JOIN foo as e on c.x = e.x
  /// </code>
  /// This allows the optimizer to choose an appropriate join ordering for evaluation.
  /// </example>
  /// </item>
  /// <item>Select * and column renaming.  In the example above, we noticed that
  /// in some cases we add <c>SELECT * FROM ...</c> to complete the SQL
  /// statement. i.e. there is no explicit PROJECT list.
  /// In this case, we enumerate all the columns available in the FROM clause
  /// This is particularly problematic in the case of Join trees, since the columns
  /// from the extents joined might have the same name - this is illegal.  To solve
  /// this problem, we will have to rename columns if they are part of a SELECT *
  /// for a JOIN node - we do not need renaming in any other situation.
  /// <see cref="SqlGenerator.AddDefaultColumns"/>.
  /// </item>
  /// </list>
  ///
  /// <para>
  /// Renaming issues.
  /// When rows or columns are renamed, we produce names that are unique globally
  /// with respect to the query.  The names are derived from the original names,
  /// with an integer as a suffix. e.g. CustomerId will be renamed to CustomerId1,
  /// CustomerId2 etc.
  ///
  /// Since the names generated are globally unique, they will not conflict when the
  /// columns of a JOIN SELECT statement are joined with another JOIN. 
  ///
  /// </para>
  ///
  /// <para>
  /// Record flattening.
  /// SQL server does not have the concept of records.  However, a join statement
  /// produces records.  We have to flatten the record accesses into a simple
  /// <c>alias.column</c> form.  <see cref="SqlGenerator.Visit(DbPropertyExpression)"/>
  /// </para>
  ///
  /// <para>
  /// Building the SQL.
  /// There are 2 phases
  /// <list type="numbered">
  /// <item>Traverse the tree, producing a sql builder <see cref="SqlBuilder"/></item>
  /// <item>Write the SqlBuilder into a string, renaming the aliases and columns
  /// as needed.</item>
  /// </list>
  ///
  /// In the first phase, we traverse the tree.  We cannot generate the SQL string
  /// right away, since
  /// <list type="bullet">
  /// <item>The WHERE clause has to be visited before the from clause.</item>
  /// <item>extent aliases and column aliases need to be renamed.  To minimize
  /// renaming collisions, all the names used must be known, before any renaming
  /// choice is made.</item>
  /// </list>
  /// To defer the renaming choices, we use symbols <see cref="Symbol"/>.  These
  /// are renamed in the second phase.
  ///
  /// Since visitor methods cannot transfer information to child nodes through
  /// parameters, we use some global stacks,
  /// <list type="bullet">
  /// <item>A stack for the current SQL select statement.  This is needed by
  /// <see cref="SqlGenerator.Visit(DbVariableReferenceExpression)"/> to create a
  /// list of free variables used by a select statement.  This is needed for
  /// alias renaming.
  /// </item>
  /// <item>A stack for the join context.  When visiting a <see cref="DbScanExpression"/>,
  /// we need to know whether we are inside a join or not.  If we are inside
  /// a join, we do not create a new SELECT statement.</item>
  /// </list>
  /// </para>
  ///
  /// <para>
  /// Global state.
  /// To enable renaming, we maintain
  /// <list type="bullet">
  /// <item>The set of all extent aliases used.</item>
  /// <item>The set of all column aliases used.</item>
  /// </list>
  ///
  /// Finally, we have a symbol table to lookup variable references.  All references
  /// to the same extent have the same symbol.
  /// </para>
  ///
  /// <para>
  /// Sql select statement sharing.
  ///
  /// Each of the relational operator nodes
  /// <list type="bullet">
  /// <item>Project</item>
  /// <item>Filter</item>
  /// <item>GroupBy</item>
  /// <item>Sort/OrderBy</item>
  /// </list>
  /// can add its non-input (e.g. project, predicate, sort order etc.) to
  /// the SQL statement for the input, or create a new SQL statement.
  /// If it chooses to reuse the input's SQL statement, we play the following
  /// symbol table trick to accomplish renaming.  The symbol table entry for
  /// the alias of the current node points to the symbol for the input in
  /// the input's SQL statement.
  /// <example>
  /// <code>
  /// Project(b.x
  ///     b = Filter(
  ///         c = Extent(foo)
  ///         c.x = 5)
  ///     )
  /// </code>
  /// The Extent node creates a new SqlSelectStatement.  This is added to the
  /// symbol table by the Filter as {c, Symbol(c)}.  Thus, <c>c.x</c> is resolved to
  /// <c>Symbol(c).x</c>.
  /// Looking at the project node, we add {b, Symbol(c)} to the symbol table if the
  /// SQL statement is reused, and {b, Symbol(b)}, if there is no reuse.
  ///
  /// Thus, <c>b.x</c> is resolved to <c>Symbol(c).x</c> if there is reuse, and to
  /// <c>Symbol(b).x</c> if there is no reuse.
  /// </example>
  /// </para>
  /// </remarks>
  internal sealed class SqlGenerator : DbExpressionVisitor<ISqlFragment>
  {
    #region Visitor parameter stacks
    /// <summary>
    /// Every relational node has to pass its SELECT statement to its children
    /// This allows them (DbVariableReferenceExpression eventually) to update the list of
    /// outer extents (free variables) used by this select statement.
    /// </summary>
    Stack<SqlSelectStatement> selectStatementStack;

    /// <summary>
    /// The top of the stack
    /// </summary>
    private SqlSelectStatement CurrentSelectStatement
    {
      // There is always something on the stack, so we can always Peek.
      get { return selectStatementStack.Peek(); }
    }

    /// <summary>
    /// Nested joins and extents need to know whether they should create
    /// a new Select statement, or reuse the parent's.  This flag
    /// indicates whether the parent is a join or not.
    /// </summary>
    Stack<bool> isParentAJoinStack;

    /// <summary>
    /// The top of the stack
    /// </summary>
    private bool IsParentAJoin
    {
      // There might be no entry on the stack if a Join node has never
      // been seen, so we return false in that case.
      get { return isParentAJoinStack.Count == 0 ? false : isParentAJoinStack.Peek(); }
    }

    #endregion

    #region Global lists and state
    Dictionary<string, int> allExtentNames;
    internal Dictionary<string, int> AllExtentNames
    {
      get { return allExtentNames; }
    }

    // For each column name, we store the last integer suffix that
    // was added to produce a unique column name.  This speeds up
    // the creation of the next unique name for this column name.
    Dictionary<string, int> allColumnNames;
    internal Dictionary<string, int> AllColumnNames
    {
      get { return allColumnNames; }
    }

    SymbolTable symbolTable = new SymbolTable();

    /// <summary>
    /// VariableReferenceExpressions are allowed only as children of DbPropertyExpression
    /// or MethodExpression.  The cheapest way to ensure this is to set the following
    /// property in DbVariableReferenceExpression and reset it in the allowed parent expressions.
    /// </summary>
    bool isVarRefSingle = false;

    #endregion

    #region Statics
    static private readonly Dictionary<string, FunctionHandler> _builtInFunctionHandlers = InitializeBuiltInFunctionHandlers();
    static private readonly Dictionary<string, FunctionHandler> _canonicalFunctionHandlers = InitializeCanonicalFunctionHandlers();
    static private readonly Dictionary<string, string> _functionNameToOperatorDictionary = InitializeFunctionNameToOperatorDictionary();
    static private readonly Dictionary<string, object> _datepartKeywords = InitializeDatepartKeywords();
    static private readonly char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    private delegate ISqlFragment FunctionHandler(SqlGenerator sqlgen, DbFunctionExpression functionExpr);

    /// <summary>
    /// All special built-in functions and their handlers
    /// </summary>
    /// <returns></returns>
    private static Dictionary<string, FunctionHandler> InitializeBuiltInFunctionHandlers()
    {
      Dictionary<string, FunctionHandler> functionHandlers = new Dictionary<string, FunctionHandler>(5, StringComparer.Ordinal);
      functionHandlers.Add("concat", HandleConcatFunction);
      functionHandlers.Add("dateadd", HandleDatepartDateFunction);
      functionHandlers.Add("datediff", HandleDatepartDateFunction);
      functionHandlers.Add("datename", HandleDatepartDateFunction);
      functionHandlers.Add("datepart", HandleDatepartDateFunction);
      return functionHandlers;
    }

    /// <summary>
    /// All special non-aggregate canonical functions and their handlers
    /// </summary>
    /// <returns></returns>
    private static Dictionary<string, FunctionHandler> InitializeCanonicalFunctionHandlers()
    {
      Dictionary<string, FunctionHandler> functionHandlers = new Dictionary<string, FunctionHandler>(16, StringComparer.Ordinal);
      functionHandlers.Add("IndexOf", HandleCanonicalFunctionIndexOf);
      functionHandlers.Add("Length", HandleCanonicalFunctionLength);
      functionHandlers.Add("NewGuid", HandleCanonicalFunctionNewGuid);
      functionHandlers.Add("Round", HandleCanonicalFunctionRound);
      functionHandlers.Add("ToLower", HandleCanonicalFunctionToLower);
      functionHandlers.Add("ToUpper", HandleCanonicalFunctionToUpper);
      functionHandlers.Add("Trim", HandleCanonicalFunctionTrim);

      //DatePartFunctions
      functionHandlers.Add("Year", HandleCanonicalFunctionDatepart);
      functionHandlers.Add("Month", HandleCanonicalFunctionDatepart);
      functionHandlers.Add("Day", HandleCanonicalFunctionDatepart);
      functionHandlers.Add("Hour", HandleCanonicalFunctionDatepart);
      functionHandlers.Add("Minute", HandleCanonicalFunctionDatepart);
      functionHandlers.Add("Second", HandleCanonicalFunctionDatepart);
      functionHandlers.Add("DateAdd", HandleCanonicalFunctionDateAdd);
      functionHandlers.Add("DateDiff", HandleCanonicalFunctionDateSubtract);

      //Functions that translate to operators
      functionHandlers.Add("Concat", HandleConcatFunction);
      functionHandlers.Add("BitwiseAnd", HandleCanonicalFunctionBitwise);
      functionHandlers.Add("BitwiseNot", HandleCanonicalFunctionBitwise);
      functionHandlers.Add("BitwiseOr", HandleCanonicalFunctionBitwise);
      functionHandlers.Add("BitwiseXor", HandleCanonicalFunctionBitwise);
      return functionHandlers;
    }

    /// <summary>
    /// Valid datepart values
    /// </summary>
    /// <returns></returns>
    private static Dictionary<string, object> InitializeDatepartKeywords()
    {
      #region Datepart Keywords
      //
      // valid datepart values
      //
      Dictionary<string, object> datepartKeywords = new Dictionary<string, object>(30, StringComparer.Ordinal);
      datepartKeywords.Add("d", null);
      datepartKeywords.Add("day", null);
      datepartKeywords.Add("dayofyear", null);
      datepartKeywords.Add("dd", null);
      datepartKeywords.Add("dw", null);
      datepartKeywords.Add("dy", null);
      datepartKeywords.Add("hh", null);
      datepartKeywords.Add("hour", null);
      datepartKeywords.Add("m", null);
      datepartKeywords.Add("mi", null);
      datepartKeywords.Add("millisecond", null);
      datepartKeywords.Add("minute", null);
      datepartKeywords.Add("mm", null);
      datepartKeywords.Add("month", null);
      datepartKeywords.Add("ms", null);
      datepartKeywords.Add("n", null);
      datepartKeywords.Add("q", null);
      datepartKeywords.Add("qq", null);
      datepartKeywords.Add("quarter", null);
      datepartKeywords.Add("s", null);
      datepartKeywords.Add("second", null);
      datepartKeywords.Add("ss", null);
      datepartKeywords.Add("week", null);
      datepartKeywords.Add("weekday", null);
      datepartKeywords.Add("wk", null);
      datepartKeywords.Add("ww", null);
      datepartKeywords.Add("y", null);
      datepartKeywords.Add("year", null);
      datepartKeywords.Add("yy", null);
      datepartKeywords.Add("yyyy", null);
      return datepartKeywords;
      #endregion
    }

    /// <summary>
    /// Initializes the mapping from functions to T-SQL operators
    /// for all functions that translate to T-SQL operators
    /// </summary>
    /// <returns></returns>
    private static Dictionary<string, string> InitializeFunctionNameToOperatorDictionary()
    {
      Dictionary<string, string> functionNameToOperatorDictionary = new Dictionary<string, string>(5, StringComparer.Ordinal);
      functionNameToOperatorDictionary.Add("Concat", "+");    //canonical
      functionNameToOperatorDictionary.Add("CONCAT", "+");    //store
      functionNameToOperatorDictionary.Add("BitwiseAnd", "&");
      functionNameToOperatorDictionary.Add("BitwiseNot", "~");
      functionNameToOperatorDictionary.Add("BitwiseOr", "|");
      functionNameToOperatorDictionary.Add("BitwiseXor", "^");
      return functionNameToOperatorDictionary;
    }

    #endregion

    #region Constructor
    /// <summary>
    /// Basic constructor. 
    /// </summary>
    private SqlGenerator()
    {
    }
    #endregion

    #region Entry points
    /// <summary>
    /// General purpose static function that can be called from System.Data assembly
    /// </summary>
    /// <param name="sqlVersion">Server version</param>
    /// <param name="tree">command tree</param>
    /// <param name="parameters">Parameters to add to the command tree corresponding
    /// to constants in the command tree. Used only in ModificationCommandTrees.</param>
    /// <returns>The string representing the SQL to be executed.</returns>
    internal static string GenerateSql(DbCommandTree tree, out List<DbParameter> parameters, out CommandType commandType)
    {
      commandType = CommandType.Text;

      //Handle Query
      DbQueryCommandTree queryCommandTree = tree as DbQueryCommandTree;
      if (queryCommandTree != null)
      {
        SqlGenerator sqlGen = new SqlGenerator();
        parameters = null;
        
        string sql = sqlGen.GenerateSql((DbQueryCommandTree)tree);

        return sql;
      }

      //Handle Function
      DbFunctionCommandTree DbFunctionCommandTree = tree as DbFunctionCommandTree;
      if (DbFunctionCommandTree != null)
      {
        SqlGenerator sqlGen = new SqlGenerator();
        parameters = null;

        string sql = sqlGen.GenerateFunctionSql(DbFunctionCommandTree, out commandType);

        return sql;
      }

      //Handle Insert
      DbInsertCommandTree insertCommandTree = tree as DbInsertCommandTree;
      if (insertCommandTree != null)
      {
        return DmlSqlGenerator.GenerateInsertSql(insertCommandTree, out parameters);
      }

      //Handle Delete
      DbDeleteCommandTree deleteCommandTree = tree as DbDeleteCommandTree;
      if (deleteCommandTree != null)
      {
        return DmlSqlGenerator.GenerateDeleteSql(deleteCommandTree, out parameters);
      }

      //Handle Update
      DbUpdateCommandTree updateCommandTree = tree as DbUpdateCommandTree;
      if (updateCommandTree != null)
      {
        return DmlSqlGenerator.GenerateUpdateSql(updateCommandTree, out parameters);
      }

      throw new NotSupportedException("Unrecognized command tree type");
    }
    #endregion

    StringBuilder _typeDefs = new StringBuilder();

    #region Driver Methods
    /// <summary>
    /// Translate a command tree to a SQL string.
    ///
    /// The input tree could be translated to either a SQL SELECT statement
    /// or a SELECT expression.  This choice is made based on the return type
    /// of the expression
    /// CollectionType => select statement
    /// non collection type => select expression
    /// </summary>
    /// <param name="tree"></param>
    /// <returns>The string representing the SQL to be executed.</returns>
    private string GenerateSql(DbQueryCommandTree tree)
    {
      tree.Validate();

      selectStatementStack = new Stack<SqlSelectStatement>();
      isParentAJoinStack = new Stack<bool>();

      allExtentNames = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
      allColumnNames = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

      // Literals will not be converted to parameters.

      ISqlFragment result;
      if (MetadataHelpers.IsCollectionType(tree.Query.ResultType))
      {
        SqlSelectStatement sqlStatement = VisitExpressionEnsureSqlStatement(tree.Query);
        Debug.Assert(sqlStatement != null, "The outer most sql statment is null");
        sqlStatement.IsTopMost = true;
        result = sqlStatement;

      }
      else
      {
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.Append("SELECT ");
        sqlBuilder.Append(tree.Query.Accept(this));

        result = sqlBuilder;
      }

      if (isVarRefSingle)
      {
        throw new NotSupportedException();
        // A DbVariableReferenceExpression has to be a child of DbPropertyExpression or MethodExpression
      }

      // Check that the parameter stacks are not leaking.
      Debug.Assert(selectStatementStack.Count == 0);
      Debug.Assert(isParentAJoinStack.Count == 0);

      if (_typeDefs.Length > 0)
      {
        _typeDefs.Insert(0x0, "TYPES ");
        _typeDefs.Append(";\r\n");
        _typeDefs.Append(WriteSql(result));
        return _typeDefs.ToString();
      }

      return WriteSql(result);
    }

    /// <summary>
    /// Translate a function command tree to a SQL string.
    /// </summary>
    private string GenerateFunctionSql(DbFunctionCommandTree tree, out CommandType commandType)
    {
      tree.Validate();

      EdmFunction function = tree.Function;

      // We expect function to always have these properties
      string userCommandText = (string)function.MetadataProperties["CommandTextAttribute"].Value;
      string userSchemaName = (string)function.MetadataProperties["Schema"].Value;
      string userFuncName = (string)function.MetadataProperties["StoreFunctionNameAttribute"].Value;

      if (String.IsNullOrEmpty(userCommandText))
      {
        // build a quoted description of the function
        commandType = CommandType.StoredProcedure;

        // if the schema name is not explicitly given, it is assumed to be the metadata namespace
        string schemaName = String.IsNullOrEmpty(userSchemaName) ?
            function.NamespaceName : userSchemaName;

        // if the function store name is not explicitly given, it is assumed to be the metadata name
        string functionName = String.IsNullOrEmpty(userFuncName) ?
            function.Name : userFuncName;

        // quote elements of function text
        string quotedSchemaName = QuoteIdentifier(schemaName);
        string quotedFunctionName = QuoteIdentifier(functionName);

        // separator
        const string schemaSeparator = ".";

        // concatenate elements of function text
        string quotedFunctionText = quotedSchemaName + schemaSeparator + quotedFunctionName;

        return quotedFunctionText;
      }
      else
      {
        // if the user has specified the command text, pass it through verbatim and choose CommandType.Text
        commandType = CommandType.Text;
        return userCommandText;
      }
    }

    /// <summary>
    /// Convert the SQL fragments to a string.
    /// We have to setup the Stream for writing.
    /// </summary>
    /// <param name="sqlStatement"></param>
    /// <returns>A string representing the SQL to be executed.</returns>
    string WriteSql(ISqlFragment sqlStatement)
    {
      StringBuilder builder = new StringBuilder(1024);
      using (SqlWriter writer = new SqlWriter(builder))
      {
        sqlStatement.WriteSql(writer, this);
      }

      return builder.ToString();
    }
    #endregion

    #region DbExpressionVisitor Members

    /// <summary>
    /// Translate(left) AND Translate(right)
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/>.</returns>
    public override ISqlFragment Visit(DbAndExpression e)
    {
      return VisitBinaryExpression(" AND ", e.Left, e.Right);
    }

    /// <summary>
    /// An apply is just like a join, so it shares the common join processing
    /// in <see cref="VisitJoinExpression"/>
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlSelectStatement"/>.</returns>
    public override ISqlFragment Visit(DbApplyExpression e)
    {
      List<DbExpressionBinding> inputs = new List<DbExpressionBinding>();
      inputs.Add(e.Input);
      inputs.Add(e.Apply);

      string joinString;
      switch (e.ExpressionKind)
      {
        case DbExpressionKind.CrossApply:
          joinString = "CROSS APPLY";
          break;

        case DbExpressionKind.OuterApply:
          joinString = "OUTER APPLY";
          break;

        default:
          Debug.Assert(false);
          throw new InvalidOperationException();
      }

      // The join condition does not exist in this case, so we use null.
      // We do not have a on clause, so we use JoinType.CrossJoin.
      return VisitJoinExpression(inputs, DbExpressionKind.CrossJoin, joinString, null);
    }

    /// <summary>
    /// For binary expressions, we delegate to <see cref="VisitBinaryExpression"/>.
    /// We handle the other expressions directly.
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/></returns>
    public override ISqlFragment Visit(DbArithmeticExpression e)
    {
      SqlBuilder result;

      switch (e.ExpressionKind)
      {
        case DbExpressionKind.Divide:
          result = VisitBinaryExpression(" / ", e.Arguments[0], e.Arguments[1]);
          break;
        case DbExpressionKind.Minus:
          result = VisitBinaryExpression(" - ", e.Arguments[0], e.Arguments[1]);
          break;
        case DbExpressionKind.Modulo:
          result = VisitBinaryExpression(" % ", e.Arguments[0], e.Arguments[1]);
          break;
        case DbExpressionKind.Multiply:
          result = VisitBinaryExpression(" * ", e.Arguments[0], e.Arguments[1]);
          break;
        case DbExpressionKind.Plus:
          result = VisitBinaryExpression(" + ", e.Arguments[0], e.Arguments[1]);
          break;

        case DbExpressionKind.UnaryMinus:
          result = new SqlBuilder();
          result.Append(" -(");
          result.Append(e.Arguments[0].Accept(this));
          result.Append(")");
          break;

        default:
          Debug.Assert(false);
          throw new InvalidOperationException();
      }

      return result;
    }

    /// <summary>
    /// If the ELSE clause is null, we do not write it out.
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/></returns>
    public override ISqlFragment Visit(DbCaseExpression e)
    {
      SqlBuilder result = new SqlBuilder();

      Debug.Assert(e.When.Count == e.Then.Count);

      result.Append("CASE");
      for (int i = 0; i < e.When.Count; ++i)
      {
        result.Append(" WHEN (");
        result.Append(e.When[i].Accept(this));
        result.Append(") THEN ");
        result.Append(e.Then[i].Accept(this));
      }
      if (e.Else != null && !(e.Else is DbNullExpression))
      {
        result.Append(" ELSE ");
        result.Append(e.Else.Accept(this));
      }

      result.Append(" END");

      return result;
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public override ISqlFragment Visit(DbCastExpression e)
    {
      SqlBuilder result = new SqlBuilder();
      result.Append(e.Argument.Accept(this));
      return result;
    }

    /// <summary>
    /// The parser generates Not(Equals(...)) for &lt;&gt;.
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/>.</returns>
    public override ISqlFragment Visit(DbComparisonExpression e)
    {
      SqlBuilder result;
      switch (e.ExpressionKind)
      {
        case DbExpressionKind.Equals:
          //if (e.Left.ResultType.EdmType.Name == "String" && e.Right.ResultType.EdmType.Name == "String")
          //  result = VisitBinaryExpression(" LIKE ", e.Left, e.Right);
          //else
            result = VisitBinaryExpression(" = ", e.Left, e.Right);
          break;
        case DbExpressionKind.LessThan:
          result = VisitBinaryExpression(" < ", e.Left, e.Right);
          break;
        case DbExpressionKind.LessThanOrEquals:
          result = VisitBinaryExpression(" <= ", e.Left, e.Right);
          break;
        case DbExpressionKind.GreaterThan:
          result = VisitBinaryExpression(" > ", e.Left, e.Right);
          break;
        case DbExpressionKind.GreaterThanOrEquals:
          result = VisitBinaryExpression(" >= ", e.Left, e.Right);
          break;
        // The parser does not generate the expression kind below.
        case DbExpressionKind.NotEquals:
          result = VisitBinaryExpression(" <> ", e.Left, e.Right);
          break;

        default:
          Debug.Assert(false);  // The constructor should have prevented this
          throw new InvalidOperationException(String.Empty);
      }

      return result;
    }

    /// <summary>
    /// Constants will be send to the store as part of the generated TSQL, not as parameters
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/>.  Strings are wrapped in single
    /// quotes and escaped.  Numbers are written literally.</returns>
    public override ISqlFragment Visit(DbConstantExpression e)
    {
      SqlBuilder result = new SqlBuilder();

      PrimitiveTypeKind typeKind;
      // Model Types can be (at the time of this implementation):
      //      Binary, Boolean, Byte, DateTime, Decimal, Double, Guid, Int16, Int32, Int64,Single, String
      if (MetadataHelpers.TryGetPrimitiveTypeKind(e.ResultType, out typeKind))
      {
        switch (typeKind)
        {
          case PrimitiveTypeKind.Int32:
            // default sql server type for integral values.
            result.Append(e.Value.ToString());
            break;

          case PrimitiveTypeKind.Binary:
            result.Append(" 0x");
            result.Append(ByteArrayToBinaryString((Byte[])e.Value));
            result.Append(" ");
            break;

          case PrimitiveTypeKind.Boolean:
            result.Append((bool)e.Value ? "1" : "0");
            break;

          case PrimitiveTypeKind.Byte:
            result.Append(e.Value.ToString());
            break;

          case PrimitiveTypeKind.DateTime:
            result.Append(EscapeSingleQuote(((System.DateTime)e.Value).ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture), false /* IsUnicode */));
            break;

          case PrimitiveTypeKind.Decimal:
            string strDecimal = ((Decimal)e.Value).ToString(CultureInfo.InvariantCulture);
            // if the decimal value has no decimal part, cast as decimal to preserve type
            // if the number has precision > int64 max precision, it will be handled as decimal by sql server
            // and does not need cast. if precision is lest then 20, then cast using Max(literal precision, sql default precision)
            if (-1 == strDecimal.IndexOf('.') && (strDecimal.TrimStart(new char[] { '-' }).Length < 20))
            {
              byte precision = (Byte)strDecimal.Length;
              FacetDescription precisionFacetDescription;
              Debug.Assert(MetadataHelpers.TryGetTypeFacetDescriptionByName(e.ResultType.EdmType, "precision", out precisionFacetDescription), "Decimal primitive type must have Precision facet");
              if (MetadataHelpers.TryGetTypeFacetDescriptionByName(e.ResultType.EdmType, "precision", out precisionFacetDescription))
              {
                if (precisionFacetDescription.DefaultValue != null)
                {
                  precision = Math.Max(precision, (byte)precisionFacetDescription.DefaultValue);
                }
              }
              Debug.Assert(precision > 0, "Precision must be greater than zero");
              result.Append(strDecimal);
            }
            else
            {
              result.Append(strDecimal);
            }
            break;

          case PrimitiveTypeKind.Double:
            result.Append(((Double)e.Value).ToString(CultureInfo.InvariantCulture));
            break;

          case PrimitiveTypeKind.Guid:
            result.Append(EscapeSingleQuote(e.Value.ToString(), false /* IsUnicode */));
            break;

          case PrimitiveTypeKind.Int16:
            result.Append(e.Value.ToString());
            break;

          case PrimitiveTypeKind.Int64:
            result.Append(e.Value.ToString());
            break;

          case PrimitiveTypeKind.Single:
            result.Append(((Single)e.Value).ToString(CultureInfo.InvariantCulture));
            break;

          case PrimitiveTypeKind.String:
            bool isUnicode = MetadataHelpers.GetFacetValueOrDefault<bool>(e.ResultType, MetadataHelpers.UnicodeFacetName, true);
            result.Append(EscapeSingleQuote(e.Value as string, isUnicode));
            break;

          default:
            // all known scalar types should been handled already.
            throw new NotSupportedException();
        }
      }
      else
      {
        throw new NotSupportedException();
      }

      return result;

    }

    /// <summary>
    /// <see cref="DbDerefExpression"/> is illegal at this stage
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public override ISqlFragment Visit(DbDerefExpression e)
    {
      throw new NotSupportedException();
    }

    /// <summary>
    /// The DISTINCT has to be added to the beginning of SqlSelectStatement.Select,
    /// but it might be too late for that.  So, we use a flag on SqlSelectStatement
    /// instead, and add the "DISTINCT" in the second phase.
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlSelectStatement"/></returns>
    public override ISqlFragment Visit(DbDistinctExpression e)
    {
      SqlSelectStatement result = VisitExpressionEnsureSqlStatement(e.Argument);

      if (!IsCompatible(result, e.ExpressionKind))
      {
        Symbol fromSymbol;
        TypeUsage inputType = MetadataHelpers.GetElementTypeUsage(e.Argument.ResultType);
        result = CreateNewSelectStatement(result, "distinct", inputType, out fromSymbol);
        AddFromSymbol(result, "distinct", fromSymbol, false);
      }

      result.IsDistinct = true;
      return result;
    }

    /// <summary>
    /// An element expression returns a scalar - so it is translated to
    /// ( Select ... )
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public override ISqlFragment Visit(DbElementExpression e)
    {
      SqlBuilder result = new SqlBuilder();
      result.Append("(");
      result.Append(VisitExpressionEnsureSqlStatement(e.Argument));
      result.Append(")");

      return result;
    }

    /// <summary>
    /// <see cref="Visit(DbUnionAllExpression)"/>
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public override ISqlFragment Visit(DbExceptExpression e)
    {
      return VisitSetOpExpression(e.Left, e.Right, "EXCEPT");
    }

    /// <summary>
    /// Only concrete expression types will be visited.
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public override ISqlFragment Visit(DbExpression e)
    {
      throw new InvalidOperationException();
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="e"></param>
    /// <returns>If we are in a Join context, returns a <see cref="SqlBuilder"/>
    /// with the extent name, otherwise, a new <see cref="SqlSelectStatement"/>
    /// with the From field set.</returns>
    public override ISqlFragment Visit(DbScanExpression e)
    {
      EntitySetBase target = e.Target;

      if (IsParentAJoin)
      {
        SqlBuilder result = new SqlBuilder();
        result.Append(GetTargetTSql(target));

        return result;
      }
      else
      {
        SqlSelectStatement result = new SqlSelectStatement();
        result.From.Append(GetTargetTSql(target));

        return result;
      }
    }


    /// <summary>
    /// Gets escaped TSql identifier describing this entity set.
    /// </summary>
    /// <returns></returns>
    internal static string GetTargetTSql(EntitySetBase entitySetBase)
    {
      // construct escaped T-SQL referencing entity set
      StringBuilder builder = new StringBuilder(50);
      string definingQuery = MetadataHelpers.TryGetValueForMetadataProperty<string>(entitySetBase, "DefiningQuery");
      if (!string.IsNullOrEmpty(definingQuery))
      {
        builder.Append("(");
        builder.Append(definingQuery);
        builder.Append(")");
      }
      else
      {
        string schemaName = MetadataHelpers.TryGetValueForMetadataProperty<string>(entitySetBase, "Schema");
        if (!string.IsNullOrEmpty(schemaName))
        {
          builder.Append(SqlGenerator.QuoteIdentifier(schemaName));
          builder.Append(".");
        }
        //else
        //{
        //  builder.Append(SqlGenerator.QuoteIdentifier(entitySetBase.EntityContainer.Name));
        //  builder.Append(".");
        //}

        string tableName = MetadataHelpers.TryGetValueForMetadataProperty<string>(entitySetBase, "Table");
        if (!string.IsNullOrEmpty(tableName))
        {
          builder.Append(SqlGenerator.QuoteIdentifier(tableName));
        }
        else
        {
          builder.Append(SqlGenerator.QuoteIdentifier(entitySetBase.Name));
        }
      }
      return builder.ToString();
    }

    /// <summary>
    /// The bodies of <see cref="Visit(DbFilterExpression)"/>, <see cref="Visit(DbGroupByExpression)"/>,
    /// <see cref="Visit(DbProjectExpression)"/>, <see cref="Visit(DbSortExpression)"/> are similar.
    /// Each does the following.
    /// <list type="number">
    /// <item> Visit the input expression</item>
    /// <item> Determine if the input's SQL statement can be reused, or a new
    /// one must be created.</item>
    /// <item>Create a new symbol table scope</item>
    /// <item>Push the Sql statement onto a stack, so that children can
    /// update the free variable list.</item>
    /// <item>Visit the non-input expression.</item>
    /// <item>Cleanup</item>
    /// </list>
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlSelectStatement"/></returns>
    public override ISqlFragment Visit(DbFilterExpression e)
    {
      return VisitFilterExpression(e.Input, e.Predicate, false);
    }

    /// <summary>
    /// Lambda functions are not supported.
    /// The functions supported are:
    /// <list type="number">
    /// <item>Canonical Functions - We recognize these by their dataspace, it is DataSpace.CSpace</item>
    /// <item>Store Functions - We recognize these by the BuiltInAttribute and not being Canonical</item>
    /// <item>User-defined Functions - All the rest except for Lambda functions</item>
    /// </list>
    /// We handle Canonical and Store functions the same way: If they are in the list of functions 
    /// that need special handling, we invoke the appropriate handler, otherwise we translate them to
    /// FunctionName(arg1, arg2, ..., argn).
    /// We translate user-defined functions to NamespaceName.FunctionName(arg1, arg2, ..., argn).
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/></returns>
    public override ISqlFragment Visit(DbFunctionExpression e)
    {
      if (e.IsLambda)
      {
        throw new NotSupportedException();
      }

      //
      // check if function requires special case processing, if so, delegates to it
      //
      if (IsSpecialBuiltInFunction(e))
      {
        return HandleSpecialBuiltInFunction(e);
      }

      if (IsSpecialCanonicalFunction(e))
      {
        return HandleSpecialCanonicalFunction(e);
      }

      return HandleFunctionDefault(e);
    }


    /// <summary>
    /// <see cref="DbEntityRefExpression"/> is illegal at this stage
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public override ISqlFragment Visit(DbEntityRefExpression e)
    {
      throw new NotSupportedException();
    }

    /// <summary>
    /// <see cref="DbRefKeyExpression"/> is illegal at this stage
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public override ISqlFragment Visit(DbRefKeyExpression e)
    {
      throw new NotSupportedException();
    }

    /// <summary>
    /// <see cref="Visit(DbFilterExpression)"/> for general details.
    /// We modify both the GroupBy and the Select fields of the SqlSelectStatement.
    /// GroupBy gets just the keys without aliases,
    /// and Select gets the keys and the aggregates with aliases.
    /// 
    /// Whenever there exists at least one aggregate with an argument that is not is not a simple
    /// <see cref="DbPropertyExpression"/>  over <see cref="DbVariableReferenceExpression"/>, 
    /// we create a nested query in which we alias the arguments to the aggregates. 
    /// That is due to the following two limitations of Sql Server:
    /// <list type="number">
    /// <item>If an expression being aggregated contains an outer reference, then that outer 
    /// reference must be the only column referenced in the expression </item>
    /// <item>Sql Server cannot perform an aggregate function on an expression containing 
    /// an aggregate or a subquery. </item>
    /// </list>
    /// 
    /// The default translation, without inner query is: 
    /// 
    ///     SELECT 
    ///         kexp1 AS key1, kexp2 AS key2,... kexpn AS keyn, 
    ///         aggf1(aexpr1) AS agg1, .. aggfn(aexprn) AS aggn
    ///     FROM input AS a
    ///     GROUP BY kexp1, kexp2, .. kexpn
    /// 
    /// When we inject an innner query, the equivalent translation is:
    /// 
    ///     SELECT 
    ///         key1 AS key1, key2 AS key2, .. keyn AS keys,  
    ///         aggf1(agg1) AS agg1, aggfn(aggn) AS aggn
    ///     FROM (
    ///             SELECT 
    ///                 kexp1 AS key1, kexp2 AS key2,... kexpn AS keyn, 
    ///                 aexpr1 AS agg1, .. aexprn AS aggn
    ///             FROM input AS a
    ///         ) as a
    ///     GROUP BY key1, key2, keyn
    /// 
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlSelectStatement"/></returns>
    public override ISqlFragment Visit(DbGroupByExpression e)
    {
      Symbol fromSymbol;
      //SqlSelectStatement result = VisitInputExpression(e.Input.Expression,
      SqlSelectStatement innerQuery = VisitInputExpression(e.Input.Expression,
          e.Input.VariableName, e.Input.VariableType, out fromSymbol);

      // GroupBy is compatible with Filter and OrderBy
      // but not with Project, GroupBy
      if (!IsCompatible(innerQuery, e.ExpressionKind))
      {
        innerQuery = CreateNewSelectStatement(innerQuery, e.Input.VariableName, e.Input.VariableType, out fromSymbol);
      }

      selectStatementStack.Push(innerQuery);
      symbolTable.EnterScope();

      AddFromSymbol(innerQuery, e.Input.VariableName, fromSymbol);
      // This line is not present for other relational nodes.
      symbolTable.Add(e.Input.GroupVariableName, fromSymbol);


      // The enumerator is shared by both the keys and the aggregates,
      // so, we do not close it in between.
      RowType groupByType = MetadataHelpers.GetEdmType<RowType>(MetadataHelpers.GetEdmType<CollectionType>(e.ResultType).TypeUsage);

      //Whenever there exists at least one aggregate with an argument that is not simply a PropertyExpression 
      // over a VarRefExpression, we need a nested query in which we alias the arguments to the aggregates.
      bool needsInnerQuery = NeedsInnerQuery(e.Aggregates);

      SqlSelectStatement result;
      if (needsInnerQuery)
      {
        //Create the inner query
        result = CreateNewSelectStatement(innerQuery, e.Input.VariableName, e.Input.VariableType, false, out fromSymbol);
        AddFromSymbol(result, e.Input.VariableName, fromSymbol, false);
      }
      else
      {
        result = innerQuery;
      }

      using (IEnumerator<EdmProperty> members = groupByType.Properties.GetEnumerator())
      {
        members.MoveNext();
        Debug.Assert(result.Select.IsEmpty);

        string separator = "";

        foreach (DbExpression key in e.Keys)
        {
          EdmProperty member = members.Current;
          string alias = QuoteIdentifier(member.Name);

          result.GroupBy.Append(separator);

          ISqlFragment keySql = key.Accept(this);

          if (!needsInnerQuery)
          {
            //Default translation: Key AS Alias
            result.Select.Append(separator);
            result.Select.AppendLine();
            result.Select.Append(keySql);
            result.Select.Append(" AS ");
            result.Select.Append(alias);

            result.GroupBy.Append(keySql);
          }
          else
          {
            // The inner query contains the default translation Key AS Alias
            innerQuery.Select.Append(separator);
            innerQuery.Select.AppendLine();
            innerQuery.Select.Append(keySql);
            innerQuery.Select.Append(" AS ");
            innerQuery.Select.Append(alias);

            //The outer resulting query projects over the key aliased in the inner query: 
            //  fromSymbol.Alias AS Alias
            result.Select.Append(separator);
            result.Select.AppendLine();
            result.Select.Append(fromSymbol);
            result.Select.Append(".");
            result.Select.Append(alias);
            result.Select.Append(" AS ");
            result.Select.Append(alias);

            result.GroupBy.Append(alias);
          }

          separator = ", ";
          members.MoveNext();
        }

        foreach (DbAggregate aggregate in e.Aggregates)
        {
          EdmProperty member = members.Current;
          string alias = QuoteIdentifier(member.Name);

          Debug.Assert(aggregate.Arguments.Count == 1);
          ISqlFragment translatedAggregateArgument = aggregate.Arguments[0].Accept(this);

          object aggregateArgument;

          if (needsInnerQuery)
          {
            //In this case the argument to the aggratete is reference to the one projected out by the
            // inner query
            SqlBuilder wrappingAggregateArgument = new SqlBuilder();
            wrappingAggregateArgument.Append(fromSymbol);
            wrappingAggregateArgument.Append(".");
            wrappingAggregateArgument.Append(alias);
            aggregateArgument = wrappingAggregateArgument;

            innerQuery.Select.Append(separator);
            innerQuery.Select.AppendLine();
            innerQuery.Select.Append(translatedAggregateArgument);
            innerQuery.Select.Append(" AS ");
            innerQuery.Select.Append(alias);
          }
          else
          {
            aggregateArgument = translatedAggregateArgument;
          }

          ISqlFragment aggregateResult = VisitAggregate(aggregate, aggregateArgument);

          result.Select.Append(separator);
          result.Select.AppendLine();
          result.Select.Append(aggregateResult);
          result.Select.Append(" AS ");
          result.Select.Append(alias);

          separator = ", ";
          members.MoveNext();
        }
      }


      symbolTable.ExitScope();
      selectStatementStack.Pop();

      return result;
    }

    /// <summary>
    /// <see cref="Visit(DbUnionAllExpression)"/>
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public override ISqlFragment Visit(DbIntersectExpression e)
    {
      return VisitSetOpExpression(e.Left, e.Right, "INTERSECT");
    }

    /// <summary>
    /// Not(IsEmpty) has to be handled specially, so we delegate to
    /// <see cref="VisitIsEmptyExpression"/>.
    ///
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/>.
    /// <code>[NOT] EXISTS( ... )</code>
    /// </returns>
    public override ISqlFragment Visit(DbIsEmptyExpression e)
    {
      return VisitIsEmptyExpression(e, false);
    }

    /// <summary>
    /// Not(IsNull) is handled specially, so we delegate to
    /// <see cref="VisitIsNullExpression"/>
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/>
    /// <code>IS [NOT] NULL</code>
    /// </returns>
    public override ISqlFragment Visit(DbIsNullExpression e)
    {
      return VisitIsNullExpression(e, false);
    }

    /// <summary>
    /// <see cref="DbIsOfExpression"/> is illegal at this stage
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/></returns>
    public override ISqlFragment Visit(DbIsOfExpression e)
    {
      throw new NotSupportedException();
    }

    /// <summary>
    /// <see cref="VisitJoinExpression"/>
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlSelectStatement"/>.</returns>
    public override ISqlFragment Visit(DbCrossJoinExpression e)
    {
      return VisitJoinExpression(e.Inputs, e.ExpressionKind, "CROSS JOIN", null);
    }

    /// <summary>
    /// <see cref="VisitJoinExpression"/>
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlSelectStatement"/>.</returns>
    public override ISqlFragment Visit(DbJoinExpression e)
    {
      #region Map join type to a string
      string joinString;
      switch (e.ExpressionKind)
      {
        case DbExpressionKind.FullOuterJoin:
          joinString = "FULL OUTER JOIN";
          break;

        case DbExpressionKind.InnerJoin:
          joinString = "INNER JOIN";
          break;

        case DbExpressionKind.LeftOuterJoin:
          joinString = "LEFT OUTER JOIN";
          break;

        default:
          Debug.Assert(false);
          joinString = null;
          break;
      }
      #endregion

      List<DbExpressionBinding> inputs = new List<DbExpressionBinding>(2);
      inputs.Add(e.Left);
      inputs.Add(e.Right);

      return VisitJoinExpression(inputs, e.ExpressionKind, joinString, e.JoinCondition);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/></returns>
    public override ISqlFragment Visit(DbLikeExpression e)
    {
      SqlBuilder result = new SqlBuilder();
      result.Append(e.Argument.Accept(this));
      result.Append(" LIKE ");
      result.Append(e.Pattern.Accept(this));

      // if the ESCAPE expression is a DbNullExpression, then that's tantamount to 
      // not having an ESCAPE at all
      if (e.Escape.ExpressionKind != DbExpressionKind.Null)
      {
        result.Append(" ESCAPE ");
        result.Append(e.Escape.Accept(this));
      }

      return result;
    }

    /// <summary>
    ///  Translates to TOP expression.
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/></returns>
    public override ISqlFragment Visit(DbLimitExpression e)
    {
      Debug.Assert(e.Limit is DbConstantExpression || e.Limit is DbParameterReferenceExpression, "DbLimitExpression.Limit is of invalid expression type");

      SqlSelectStatement result = VisitExpressionEnsureSqlStatement(e.Argument, false);
      Symbol fromSymbol;

      if (!IsCompatible(result, e.ExpressionKind))
      {
        TypeUsage inputType = MetadataHelpers.GetElementTypeUsage(e.Argument.ResultType);

        result = CreateNewSelectStatement(result, "top", inputType, out fromSymbol);
        AddFromSymbol(result, "top", fromSymbol, false);
      }

      ISqlFragment topCount = HandaleCountExpression(e.Limit);

      result.Top = new TopClause(topCount, e.WithTies);
      return result;
    }

    /// <summary>
    /// DbNewInstanceExpression is allowed as a child of DbProjectExpression only.
    /// If anyone else is the parent, we throw.
    /// We also perform special casing for collections - where we could convert
    /// them into Unions
    ///
    /// <see cref="VisitNewInstanceExpression"/> for the actual implementation.
    ///
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public override ISqlFragment Visit(DbNewInstanceExpression e)
    {
      if (MetadataHelpers.IsCollectionType(e.ResultType))
      {
        return VisitCollectionConstructor(e);
      }
      throw new NotSupportedException();
    }

    /// <summary>
    /// The Not expression may cause the translation of its child to change.
    /// These children are
    /// <list type="bullet">
    /// <item><see cref="DbNotExpression"/>NOT(Not(x)) becomes x</item>
    /// <item><see cref="DbIsEmptyExpression"/>NOT EXISTS becomes EXISTS</item>
    /// <item><see cref="DbIsNullExpression"/>IS NULL becomes IS NOT NULL</item>
    /// <item><see cref="DbComparisonExpression"/>= becomes&lt;&gt; </item>
    /// </list>
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/></returns>
    public override ISqlFragment Visit(DbNotExpression e)
    {
      // Flatten Not(Not(x)) to x.
      DbNotExpression notExpression = e.Argument as DbNotExpression;
      if (notExpression != null)
      {
        return notExpression.Argument.Accept(this);
      }

      DbIsEmptyExpression isEmptyExpression = e.Argument as DbIsEmptyExpression;
      if (isEmptyExpression != null)
      {
        return VisitIsEmptyExpression(isEmptyExpression, true);
      }

      DbIsNullExpression isNullExpression = e.Argument as DbIsNullExpression;
      if (isNullExpression != null)
      {
        return VisitIsNullExpression(isNullExpression, true);
      }

      DbComparisonExpression comparisonExpression = e.Argument as DbComparisonExpression;
      if (comparisonExpression != null)
      {
        if (comparisonExpression.ExpressionKind == DbExpressionKind.Equals)
        {
          return VisitBinaryExpression(" <> ", comparisonExpression.Left, comparisonExpression.Right);
        }
      }

      SqlBuilder result = new SqlBuilder();
      result.Append(" NOT (");
      result.Append(e.Argument.Accept(this));
      result.Append(")");

      return result;
    }

    /// <summary>
    /// </summary>
    /// <param name="e"></param>
    /// <returns><see cref="SqlBuilder"/></returns>
    public override ISqlFragment Visit(DbNullExpression e)
    {
      SqlBuilder result = new SqlBuilder();
      // always cast nulls - sqlserver doesn't like case expressions where the "then" clause is null
      result.Append("NULL");
      return result;
    }

    /// <summary>
    /// <see cref="DbOfTypeExpression"/> is illegal at this stage
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/></returns>
    public override ISqlFragment Visit(DbOfTypeExpression e)
    {
      throw new NotSupportedException();
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/></returns>
    /// <seealso cref="Visit(DbAndExpression)"/>
    public override ISqlFragment Visit(DbOrExpression e)
    {
      return VisitBinaryExpression(" OR ", e.Left, e.Right);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/></returns>
    public override ISqlFragment Visit(DbParameterReferenceExpression e)
    {
      SqlBuilder result = new SqlBuilder();
      // Do not quote this name.
      // We are not checking that e.Name has no illegal characters. e.g. space
      result.Append("@" + e.ParameterName);

      return result;
    }

    /// <summary>
    /// <see cref="Visit(DbFilterExpression)"/> for the general ideas.
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlSelectStatement"/></returns>
    /// <seealso cref="Visit(DbFilterExpression)"/>
    public override ISqlFragment Visit(DbProjectExpression e)
    {
      Symbol fromSymbol;
      SqlSelectStatement result = VisitInputExpression(e.Input.Expression, e.Input.VariableName, e.Input.VariableType, out fromSymbol);

      // Project is compatible with Filter
      // but not with Project, GroupBy
      if (!IsCompatible(result, e.ExpressionKind))
      {
        result = CreateNewSelectStatement(result, e.Input.VariableName, e.Input.VariableType, out fromSymbol);
      }

      selectStatementStack.Push(result);
      symbolTable.EnterScope();

      AddFromSymbol(result, e.Input.VariableName, fromSymbol);

      // Project is the only node that can have DbNewInstanceExpression as a child
      // so we have to check it here.
      // We call VisitNewInstanceExpression instead of Visit(DbNewInstanceExpression), since
      // the latter throws.
      DbNewInstanceExpression newInstanceExpression = e.Projection as DbNewInstanceExpression;
      if (newInstanceExpression != null)
      {
        result.Select.Append(VisitNewInstanceExpression(newInstanceExpression));
      }
      else
      {
        result.Select.Append(e.Projection.Accept(this));
      }

      symbolTable.ExitScope();
      selectStatementStack.Pop();

      return result;
    }

    /// <summary>
    /// This method handles record flattening, which works as follows.
    /// consider an expression <c>Prop(y, Prop(x, Prop(d, Prop(c, Prop(b, Var(a)))))</c>
    /// where a,b,c are joins, d is an extent and x and y are fields.
    /// b has been flattened into a, and has its own SELECT statement.
    /// c has been flattened into b.
    /// d has been flattened into c.
    ///
    /// We visit the instance, so we reach Var(a) first.  This gives us a (join)symbol.
    /// Symbol(a).b gives us a join symbol, with a SELECT statement i.e. Symbol(b).
    /// From this point on , we need to remember Symbol(b) as the source alias,
    /// and then try to find the column.  So, we use a SymbolPair.
    ///
    /// We have reached the end when the symbol no longer points to a join symbol.
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="JoinSymbol"/> if we have not reached the first
    /// Join node that has a SELECT statement.
    /// A <see cref="SymbolPair"/> if we have seen the JoinNode, and it has
    /// a SELECT statement.
    /// A <see cref="SqlBuilder"/> with {Input}.propertyName otherwise.
    /// </returns>
    public override ISqlFragment Visit(DbPropertyExpression e)
    {
      SqlBuilder result;

      ISqlFragment instanceSql = e.Instance.Accept(this);

      // Since the DbVariableReferenceExpression is a proper child of ours, we can reset
      // isVarSingle.
      DbVariableReferenceExpression DbVariableReferenceExpression = e.Instance as DbVariableReferenceExpression;
      if (DbVariableReferenceExpression != null)
      {
        isVarRefSingle = false;
      }

      // We need to flatten, and have not yet seen the first nested SELECT statement.
      JoinSymbol joinSymbol = instanceSql as JoinSymbol;
      if (joinSymbol != null)
      {
        Debug.Assert(joinSymbol.NameToExtent.ContainsKey(e.Property.Name));
        if (joinSymbol.IsNestedJoin)
        {
          return new SymbolPair(joinSymbol, joinSymbol.NameToExtent[e.Property.Name]);
        }
        else
        {
          return joinSymbol.NameToExtent[e.Property.Name];
        }
      }

      // ---------------------------------------
      // We have seen the first nested SELECT statement, but not the column.
      SymbolPair symbolPair = instanceSql as SymbolPair;
      if (symbolPair != null)
      {
        JoinSymbol columnJoinSymbol = symbolPair.Column as JoinSymbol;
        if (columnJoinSymbol != null)
        {
          symbolPair.Column = columnJoinSymbol.NameToExtent[e.Property.Name];
          return symbolPair;
        }
        else
        {
          // symbolPair.Column has the base extent.
          // we need the symbol for the column, since it might have been renamed
          // when handling a JOIN.
          if (symbolPair.Column.Columns.ContainsKey(e.Property.Name))
          {
            result = new SqlBuilder();
            result.Append(symbolPair.Source);
            result.Append(".");
            result.Append(symbolPair.Column.Columns[e.Property.Name]);
            return result;
          }
        }
      }
      // ---------------------------------------

      result = new SqlBuilder();
      result.Append(instanceSql);
      result.Append(".");

      // At this point the column name cannot be renamed, so we do
      // not use a symbol.
      result.Append(QuoteIdentifier(e.Property.Name));

      return result;
    }

    /// <summary>
    /// Any(input, x) => Exists(Filter(input,x))
    /// All(input, x) => Not Exists(Filter(input, not(x))
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public override ISqlFragment Visit(DbQuantifierExpression e)
    {
      SqlBuilder result = new SqlBuilder();

      bool negatePredicate = (e.ExpressionKind == DbExpressionKind.All);
      if (e.ExpressionKind == DbExpressionKind.Any)
      {
        result.Append("EXISTS (");
      }
      else
      {
        Debug.Assert(e.ExpressionKind == DbExpressionKind.All);
        result.Append("NOT EXISTS (");
      }

      SqlSelectStatement filter = VisitFilterExpression(e.Input, e.Predicate, negatePredicate);
      if (filter.Select.IsEmpty)
      {
        AddDefaultColumns(filter);
      }

      result.Append(filter);
      result.Append(")");

      return result;
    }

    /// <summary>
    /// <see cref="DbRefExpression"/> is illegal at this stage
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public override ISqlFragment Visit(DbRefExpression e)
    {
      throw new NotSupportedException();
    }

    /// <summary>
    /// <see cref="DbRelationshipNavigationExpression"/> is illegal at this stage
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public override ISqlFragment Visit(DbRelationshipNavigationExpression e)
    {
      throw new NotSupportedException();
    }

    /// <summary>
    /// For Sql9 it translates to:
    /// SELECT Y.x1, Y.x2, ..., Y.xn
    /// FROM (
    ///     SELECT X.x1, X.x2, ..., X.xn, row_number() OVER (ORDER BY sk1, sk2, ...) AS [row_number] 
    ///     FROM input as X 
    ///     ) as Y
    /// WHERE Y.[row_number] > count 
    /// ORDER BY sk1, sk2, ...
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/></returns>
    public override ISqlFragment Visit(DbSkipExpression e)
    {
      Debug.Assert(e.Count is DbConstantExpression || e.Count is DbParameterReferenceExpression, "DbSkipExpression.Count is of invalid expression type");

      //Visit the input
      Symbol fromSymbol;
      SqlSelectStatement input = VisitInputExpression(e.Input.Expression, e.Input.VariableName, e.Input.VariableType, out fromSymbol);

      // Skip is not compatible with anything that OrderBy is not compatible with, as well as with distinct
      if (!IsCompatible(input, e.ExpressionKind))
      {
        input = CreateNewSelectStatement(input, e.Input.VariableName, e.Input.VariableType, out fromSymbol);
      }

      selectStatementStack.Push(input);
      symbolTable.EnterScope();

      AddFromSymbol(input, e.Input.VariableName, fromSymbol);

      //Add the default columns
      Debug.Assert(input.Select.IsEmpty);
      List<Symbol> inputColumns = AddDefaultColumns(input);

      input.Select.Append(", row_number() OVER (ORDER BY ");
      AddSortKeys(input.Select, e.SortOrder);
      input.Select.Append(") AS ");

      Symbol row_numberSymbol = new Symbol("row_number", null);

      input.Select.Append(row_numberSymbol);

      //The inner statement is complete, its scopes need not be valid any longer
      symbolTable.ExitScope();
      selectStatementStack.Pop();

      //Create the resulting statement 
      //See CreateNewSelectStatement, it is very similar

      SqlSelectStatement result = new SqlSelectStatement();
      result.From.Append("( ");
      result.From.Append(input);
      result.From.AppendLine();
      result.From.Append(") ");

      //Create a symbol for the input
      Symbol resultFromSymbol = null;

      if (input.FromExtents.Count == 1)
      {
        JoinSymbol oldJoinSymbol = input.FromExtents[0] as JoinSymbol;
        if (oldJoinSymbol != null)
        {
          // Note: input.FromExtents will not do, since it might
          // just be an alias of joinSymbol, and we want an actual JoinSymbol.
          JoinSymbol newJoinSymbol = new JoinSymbol(e.Input.VariableName, e.Input.VariableType, oldJoinSymbol.ExtentList);
          // This indicates that the oldStatement is a blocking scope
          // i.e. it hides/renames extent columns
          newJoinSymbol.IsNestedJoin = true;
          newJoinSymbol.ColumnList = inputColumns;
          newJoinSymbol.FlattenedExtentList = oldJoinSymbol.FlattenedExtentList;

          resultFromSymbol = newJoinSymbol;
        }
      }

      if (resultFromSymbol == null)
      {
        // This is just a simple extent/SqlSelectStatement,
        // and we can get the column list from the type.
        resultFromSymbol = new Symbol(e.Input.VariableName, e.Input.VariableType);
      }
      //Add the ORDER BY part
      selectStatementStack.Push(result);
      symbolTable.EnterScope();

      AddFromSymbol(result, e.Input.VariableName, resultFromSymbol);

      //Add the predicate 
      result.Where.Append(resultFromSymbol);
      result.Where.Append(".");
      result.Where.Append(row_numberSymbol);
      result.Where.Append(" > ");
      result.Where.Append(HandaleCountExpression(e.Count));

      AddSortKeys(result.OrderBy, e.SortOrder);

      symbolTable.ExitScope();
      selectStatementStack.Pop();

      return result;
    }

    /// <summary>
    /// <see cref="Visit(DbFilterExpression)"/>
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlSelectStatement"/></returns>
    /// <seealso cref="Visit(DbFilterExpression)"/>
    public override ISqlFragment Visit(DbSortExpression e)
    {
      Symbol fromSymbol;
      SqlSelectStatement result = VisitInputExpression(e.Input.Expression, e.Input.VariableName, e.Input.VariableType, out fromSymbol);

      // OrderBy is compatible with Filter
      // and nothing else
      if (!IsCompatible(result, e.ExpressionKind))
      {
        result = CreateNewSelectStatement(result, e.Input.VariableName, e.Input.VariableType, out fromSymbol);
      }

      selectStatementStack.Push(result);
      symbolTable.EnterScope();

      AddFromSymbol(result, e.Input.VariableName, fromSymbol);

      AddSortKeys(result.OrderBy, e.SortOrder);

      symbolTable.ExitScope();
      selectStatementStack.Pop();

      return result;
    }

    /// <summary>
    /// <see cref="DbTreatExpression"/> is illegal at this stage
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="SqlBuilder"/></returns>
    public override ISqlFragment Visit(DbTreatExpression e)
    {
      throw new NotSupportedException();
    }

    /// <summary>
    /// This code is shared by <see cref="Visit(DbExceptExpression)"/>
    /// and <see cref="Visit(DbIntersectExpression)"/>
    ///
    /// <see cref="VisitSetOpExpression"/>
    /// Since the left and right expression may not be Sql select statements,
    /// we must wrap them up to look like SQL select statements.
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public override ISqlFragment Visit(DbUnionAllExpression e)
    {
      return VisitSetOpExpression(e.Left, e.Right, "UNION ALL");
    }

    /// <summary>
    /// This method determines whether an extent from an outer scope(free variable)
    /// is used in the CurrentSelectStatement.
    ///
    /// An extent in an outer scope, if its symbol is not in the FromExtents
    /// of the CurrentSelectStatement.
    /// </summary>
    /// <param name="e"></param>
    /// <returns>A <see cref="Symbol"/>.</returns>
    public override ISqlFragment Visit(DbVariableReferenceExpression e)
    {
      if (isVarRefSingle)
      {
        throw new NotSupportedException();
        // A DbVariableReferenceExpression has to be a child of DbPropertyExpression or MethodExpression
        // This is also checked in GenerateSql(...) at the end of the visiting.
      }
      isVarRefSingle = true; // This will be reset by DbPropertyExpression or MethodExpression

      Symbol result = symbolTable.Lookup(e.VariableName);
      if (!CurrentSelectStatement.FromExtents.Contains(result))
      {
        CurrentSelectStatement.OuterExtents[result] = true;
      }

      return result;
    }

    #region Visits shared by multiple nodes
    /// <summary>
    /// Aggregates are not visited by the normal visitor walk.
    /// </summary>
    /// <param name="aggregate">The aggreate go be translated</param>
    /// <param name="aggregateArgument">The translated aggregate argument</param>
    /// <returns></returns>
    SqlBuilder VisitAggregate(DbAggregate aggregate, object aggregateArgument)
    {
      SqlBuilder aggregateResult = new SqlBuilder();
      DbFunctionAggregate functionAggregate = aggregate as DbFunctionAggregate;

      if (functionAggregate == null)
      {
        throw new NotSupportedException();
      }

      //The only aggregate function with different name is Big_Count
      //Note: If another such function is to be added, a dictionary should be created
      if (MetadataHelpers.IsCanonicalFunction(functionAggregate.Function)
          && String.Equals(functionAggregate.Function.Name, "BigCount", StringComparison.Ordinal))
      {
        aggregateResult.Append("COUNT_BIG");
      }
      else
      {
        WriteFunctionName(aggregateResult, functionAggregate.Function);
      }

      aggregateResult.Append("(");

      DbFunctionAggregate fnAggr = functionAggregate;
      if ((null != fnAggr) && (fnAggr.Distinct))
      {
        aggregateResult.Append("DISTINCT ");
      }

      aggregateResult.Append(aggregateArgument);

      aggregateResult.Append(")");
      return aggregateResult;
    }


    SqlBuilder VisitBinaryExpression(string op, DbExpression left, DbExpression right)
    {
      SqlBuilder result = new SqlBuilder();
      if (IsComplexExpression(left))
      {
        result.Append("(");
      }

      result.Append(left.Accept(this));

      if (IsComplexExpression(left))
      {
        result.Append(")");
      }

      result.Append(op);

      if (IsComplexExpression(right))
      {
        result.Append("(");
      }

      result.Append(right.Accept(this));

      if (IsComplexExpression(right))
      {
        result.Append(")");
      }

      return result;
    }

    /// <summary>
    /// This is called by the relational nodes.  It does the following
    /// <list>
    /// <item>If the input is not a SqlSelectStatement, it assumes that the input
    /// is a collection expression, and creates a new SqlSelectStatement </item>
    /// </list>
    /// </summary>
    /// <param name="inputExpression"></param>
    /// <param name="inputVarName"></param>
    /// <param name="inputVarType"></param>
    /// <param name="fromSymbol"></param>
    /// <returns>A <see cref="SqlSelectStatement"/> and the main fromSymbol
    /// for this select statement.</returns>
    SqlSelectStatement VisitInputExpression(DbExpression inputExpression,
        string inputVarName, TypeUsage inputVarType, out Symbol fromSymbol)
    {
      SqlSelectStatement result;
      ISqlFragment sqlFragment = inputExpression.Accept(this);
      result = sqlFragment as SqlSelectStatement;

      if (result == null)
      {
        result = new SqlSelectStatement();
        WrapNonQueryExtent(result, sqlFragment, inputExpression.ExpressionKind);
      }

      if (result.FromExtents.Count == 0)
      {
        // input was an extent
        fromSymbol = new Symbol(inputVarName, inputVarType);
      }
      else if (result.FromExtents.Count == 1)
      {
        // input was Filter/GroupBy/Project/OrderBy
        // we are likely to reuse this statement.
        fromSymbol = result.FromExtents[0];
      }
      else
      {
        // input was a join.
        // we are reusing the select statement produced by a Join node
        // we need to remove the original extents, and replace them with a
        // new extent with just the Join symbol.
        JoinSymbol joinSymbol = new JoinSymbol(inputVarName, inputVarType, result.FromExtents);
        joinSymbol.FlattenedExtentList = result.AllJoinExtents;

        fromSymbol = joinSymbol;
        result.FromExtents.Clear();
        result.FromExtents.Add(fromSymbol);
      }

      return result;
    }

    /// <summary>
    /// <see cref="Visit(DbIsEmptyExpression)"/>
    /// </summary>
    /// <param name="e"></param>
    /// <param name="negate">Was the parent a DbNotExpression?</param>
    /// <returns></returns>
    SqlBuilder VisitIsEmptyExpression(DbIsEmptyExpression e, bool negate)
    {
      SqlBuilder result = new SqlBuilder();
      if (!negate)
      {
        result.Append(" NOT");
      }
      result.Append(" EXISTS (");
      result.Append(VisitExpressionEnsureSqlStatement(e.Argument));
      result.AppendLine();
      result.Append(")");

      return result;
    }


    /// <summary>
    /// Translate a NewInstance(Element(X)) expression into
    ///   "select top(1) * from X"
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    private ISqlFragment VisitCollectionConstructor(DbNewInstanceExpression e)
    {
      Debug.Assert(e.Arguments.Count <= 1);

      if (e.Arguments.Count == 1 && e.Arguments[0].ExpressionKind == DbExpressionKind.Element)
      {
        DbElementExpression elementExpr = e.Arguments[0] as DbElementExpression;
        SqlSelectStatement result = VisitExpressionEnsureSqlStatement(elementExpr.Argument);

        if (!IsCompatible(result, DbExpressionKind.Element))
        {
          Symbol fromSymbol;
          TypeUsage inputType = MetadataHelpers.GetElementTypeUsage(elementExpr.Argument.ResultType);

          result = CreateNewSelectStatement(result, "element", inputType, out fromSymbol);
          AddFromSymbol(result, "element", fromSymbol, false);
        }
        result.Top = new TopClause(1, false);
        return result;
      }


      // Otherwise simply build this out as a union-all ladder
      CollectionType collectionType = MetadataHelpers.GetEdmType<CollectionType>(e.ResultType);
      Debug.Assert(collectionType != null);
      bool isScalarElement = MetadataHelpers.IsPrimitiveType(collectionType.TypeUsage);

      SqlBuilder resultSql = new SqlBuilder();
      string separator = "";

      // handle empty table
      if (e.Arguments.Count == 0)
      {
        Debug.Assert(isScalarElement);
        resultSql.Append(" SELECT NULL");
        resultSql.Append(" AS X FROM (SELECT 1) AS Y WHERE 1=0");
      }

      foreach (DbExpression arg in e.Arguments)
      {
        resultSql.Append(separator);
        resultSql.Append(" SELECT ");
        resultSql.Append(arg.Accept(this));
        // For scalar elements, no alias is appended yet. Add this.
        if (isScalarElement)
        {
          resultSql.Append(" AS X ");
        }
        separator = " UNION ALL ";
      }

      return resultSql;
    }


    /// <summary>
    /// <see cref="Visit(DbIsNullExpression)"/>
    /// </summary>
    /// <param name="e"></param>
    /// <param name="negate">Was the parent a DbNotExpression?</param>
    /// <returns></returns>
    SqlBuilder VisitIsNullExpression(DbIsNullExpression e, bool negate)
    {
      SqlBuilder result = new SqlBuilder();
      result.Append(e.Argument.Accept(this));
      if (!negate)
      {
        result.Append(" IS NULL");
      }
      else
      {
        result.Append(" IS NOT NULL");
      }

      return result;
    }

    /// <summary>
    /// This handles the processing of join expressions.
    /// The extents on a left spine are flattened, while joins
    /// not on the left spine give rise to new nested sub queries.
    ///
    /// Joins work differently from the rest of the visiting, in that
    /// the parent (i.e. the join node) creates the SqlSelectStatement
    /// for the children to use.
    ///
    /// The "parameter" IsInJoinContext indicates whether a child extent should
    /// add its stuff to the existing SqlSelectStatement, or create a new SqlSelectStatement
    /// By passing true, we ask the children to add themselves to the parent join,
    /// by passing false, we ask the children to create new Select statements for
    /// themselves.
    ///
    /// This method is called from <see cref="Visit(DbApplyExpression)"/> and
    /// <see cref="Visit(DbJoinExpression)"/>.
    /// </summary>
    /// <param name="inputs"></param>
    /// <param name="joinKind"></param>
    /// <param name="joinString"></param>
    /// <param name="joinCondition"></param>
    /// <returns> A <see cref="SqlSelectStatement"/></returns>
    ISqlFragment VisitJoinExpression(IList<DbExpressionBinding> inputs, DbExpressionKind joinKind,
        string joinString, DbExpression joinCondition)
    {
      SqlSelectStatement result;
      // If the parent is not a join( or says that it is not),
      // we should create a new SqlSelectStatement.
      // otherwise, we add our child extents to the parent's FROM clause.
      if (!IsParentAJoin)
      {
        result = new SqlSelectStatement();
        result.AllJoinExtents = new List<Symbol>();
        selectStatementStack.Push(result);
      }
      else
      {
        result = CurrentSelectStatement;
      }

      // Process each of the inputs, and then the joinCondition if it exists.
      // It would be nice if we could call VisitInputExpression - that would
      // avoid some code duplication
      // but the Join postprocessing is messy and prevents this reuse.
      symbolTable.EnterScope();

      string separator = "";
      bool isLeftMostInput = true;
      int inputCount = inputs.Count;
      for (int idx = 0; idx < inputCount; idx++)
      {
        DbExpressionBinding input = inputs[idx];

        if (separator != "")
        {
          result.From.AppendLine();
        }
        result.From.Append(separator + " ");
        // Change this if other conditions are required
        // to force the child to produce a nested SqlStatement.
        bool needsJoinContext = (input.Expression.ExpressionKind == DbExpressionKind.Scan)
                                || (isLeftMostInput &&
                                    (IsJoinExpression(input.Expression)
                                     || IsApplyExpression(input.Expression)))
                                ;

        isParentAJoinStack.Push(needsJoinContext ? true : false);
        // if the child reuses our select statement, it will append the from
        // symbols to our FromExtents list.  So, we need to remember the
        // start of the child's entries.
        int fromSymbolStart = result.FromExtents.Count;

        ISqlFragment fromExtentFragment = input.Expression.Accept(this);

        isParentAJoinStack.Pop();

        ProcessJoinInputResult(fromExtentFragment, result, input, fromSymbolStart);
        separator = joinString;

        isLeftMostInput = false;
      }

      // Visit the on clause/join condition.
      switch (joinKind)
      {
        case DbExpressionKind.FullOuterJoin:
        case DbExpressionKind.InnerJoin:
        case DbExpressionKind.LeftOuterJoin:
          result.From.Append(" ON ");
          isParentAJoinStack.Push(false);
          result.From.Append(joinCondition.Accept(this));
          isParentAJoinStack.Pop();
          break;
      }

      symbolTable.ExitScope();

      if (!IsParentAJoin)
      {
        selectStatementStack.Pop();
      }

      return result;
    }

    /// <summary>
    /// This is called from <see cref="VisitJoinExpression"/>.
    ///
    /// This is responsible for maintaining the symbol table after visiting
    /// a child of a join expression.
    ///
    /// The child's sql statement may need to be completed.
    ///
    /// The child's result could be one of
    /// <list type="number">
    /// <item>The same as the parent's - this is treated specially.</item>
    /// <item>A sql select statement, which may need to be completed</item>
    /// <item>An extent - just copy it to the from clause</item>
    /// <item>Anything else (from a collection-valued expression) -
    /// unnest and copy it.</item>
    /// </list>
    ///
    /// If the input was a Join, we need to create a new join symbol,
    /// otherwise, we create a normal symbol.
    ///
    /// We then call AddFromSymbol to add the AS clause, and update the symbol table.
    ///
    ///
    ///
    /// If the child's result was the same as the parent's, we have to clean up
    /// the list of symbols in the FromExtents list, since this contains symbols from
    /// the children of both the parent and the child.
    /// The happens when the child visited is a Join, and is the leftmost child of
    /// the parent.
    /// </summary>
    /// <param name="fromExtentFragment"></param>
    /// <param name="result"></param>
    /// <param name="input"></param>
    /// <param name="fromSymbolStart"></param>
    void ProcessJoinInputResult(ISqlFragment fromExtentFragment, SqlSelectStatement result,
        DbExpressionBinding input, int fromSymbolStart)
    {
      Symbol fromSymbol = null;

      if (result != fromExtentFragment)
      {
        // The child has its own select statement, and is not reusing
        // our select statement.
        // This should look a lot like VisitInputExpression().
        SqlSelectStatement sqlSelectStatement = fromExtentFragment as SqlSelectStatement;
        if (sqlSelectStatement != null)
        {
          if (sqlSelectStatement.Select.IsEmpty)
          {
            List<Symbol> columns = AddDefaultColumns(sqlSelectStatement);

            if (IsJoinExpression(input.Expression)
                || IsApplyExpression(input.Expression))
            {
              List<Symbol> extents = sqlSelectStatement.FromExtents;
              JoinSymbol newJoinSymbol = new JoinSymbol(input.VariableName, input.VariableType, extents);
              newJoinSymbol.IsNestedJoin = true;
              newJoinSymbol.ColumnList = columns;

              fromSymbol = newJoinSymbol;
            }
            else
            {
              // this is a copy of the code in CreateNewSelectStatement.

              // if the oldStatement has a join as its input, ...
              // clone the join symbol, so that we "reuse" the
              // join symbol.  Normally, we create a new symbol - see the next block
              // of code.
              JoinSymbol oldJoinSymbol = sqlSelectStatement.FromExtents[0] as JoinSymbol;
              if (oldJoinSymbol != null)
              {
                // Note: sqlSelectStatement.FromExtents will not do, since it might
                // just be an alias of joinSymbol, and we want an actual JoinSymbol.
                JoinSymbol newJoinSymbol = new JoinSymbol(input.VariableName, input.VariableType, oldJoinSymbol.ExtentList);
                // This indicates that the sqlSelectStatement is a blocking scope
                // i.e. it hides/renames extent columns
                newJoinSymbol.IsNestedJoin = true;
                newJoinSymbol.ColumnList = columns;
                newJoinSymbol.FlattenedExtentList = oldJoinSymbol.FlattenedExtentList;

                fromSymbol = newJoinSymbol;
              }
            }

          }
          result.From.Append(" (");
          result.From.Append(sqlSelectStatement);
          result.From.Append(" )");
        }
        else if (input.Expression is DbScanExpression)
        {
          result.From.Append(fromExtentFragment);
        }
        else // bracket it
        {
          WrapNonQueryExtent(result, fromExtentFragment, input.Expression.ExpressionKind);
        }

        if (fromSymbol == null) // i.e. not a join symbol
        {
          fromSymbol = new Symbol(input.VariableName, input.VariableType);
        }


        AddFromSymbol(result, input.VariableName, fromSymbol);
        result.AllJoinExtents.Add(fromSymbol);
      }
      else // result == fromExtentFragment.  The child extents have been merged into the parent's.
      {
        // we are adding extents to the current sql statement via flattening.
        // We are replacing the child's extents with a single Join symbol.
        // The child's extents are all those following the index fromSymbolStart.
        //
        List<Symbol> extents = new List<Symbol>();

        // We cannot call extents.AddRange, since the is no simple way to
        // get the range of symbols fromSymbolStart..result.FromExtents.Count
        // from result.FromExtents.
        // We copy these symbols to create the JoinSymbol later.
        for (int i = fromSymbolStart; i < result.FromExtents.Count; ++i)
        {
          extents.Add(result.FromExtents[i]);
        }
        result.FromExtents.RemoveRange(fromSymbolStart, result.FromExtents.Count - fromSymbolStart);
        fromSymbol = new JoinSymbol(input.VariableName, input.VariableType, extents);
        result.FromExtents.Add(fromSymbol);
        // this Join Symbol does not have its own select statement, so we
        // do not set IsNestedJoin


        // We do not call AddFromSymbol(), since we do not want to add
        // "AS alias" to the FROM clause- it has been done when the extent was added earlier.
        symbolTable.Add(input.VariableName, fromSymbol);
      }
    }

    /// <summary>
    /// We assume that this is only called as a child of a Project.
    ///
    /// This replaces <see cref="Visit(DbNewInstanceExpression)"/>, since
    /// we do not allow DbNewInstanceExpression as a child of any node other than
    /// DbProjectExpression.
    ///
    /// We write out the translation of each of the columns in the record.
    /// </summary>
    /// <param name="e"></param>

    /// <returns>A <see cref="SqlBuilder"/></returns>
    ISqlFragment VisitNewInstanceExpression(DbNewInstanceExpression e)
    {
      SqlBuilder result = new SqlBuilder();
      RowType rowType = e.ResultType.EdmType as RowType;

      if (null != rowType)
      {
        _typeDefs.Length = 0;
        ReadOnlyMetadataCollection<EdmProperty> members = rowType.Properties;
        string separator = "";
        for (int i = 0; i < e.Arguments.Count; ++i)
        {
          DbExpression argument = e.Arguments[i];
          if (MetadataHelpers.IsRowType(argument.ResultType))
          {
            // We do not support nested records or other complex objects.
            throw new NotSupportedException();
          }

          EdmProperty member = members[i];
          _typeDefs.Append(separator);
          _typeDefs.Append(GetSqlPrimitiveType(member.TypeUsage));
          result.Append(separator);
          result.AppendLine();
          result.Append(argument.Accept(this));
          result.Append(" AS ");
          result.Append(QuoteIdentifier(member.Name));
          separator = ", ";
        }
      }
      else
      {
        //
        // Types other then RowType (such as UDTs for instance) are not supported.
        //
        throw new NotSupportedException();
      }

      return result;
    }

    ISqlFragment VisitSetOpExpression(DbExpression left, DbExpression right, string separator)
    {

      SqlSelectStatement leftSelectStatement = VisitExpressionEnsureSqlStatement(left);
      SqlSelectStatement rightSelectStatement = VisitExpressionEnsureSqlStatement(right);

      SqlBuilder setStatement = new SqlBuilder();
      setStatement.Append(leftSelectStatement);
      setStatement.AppendLine();
      setStatement.Append(separator); // e.g. UNION ALL
      setStatement.AppendLine();
      setStatement.Append(rightSelectStatement);

      return setStatement;
    }


    #endregion


    #region Function Handling Helpers
    /// <summary>
    /// Determines whether the given function is a built-in function that requires special handling
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    private bool IsSpecialBuiltInFunction(DbFunctionExpression e)
    {
      return IsBuiltinFunction(e.Function) && _builtInFunctionHandlers.ContainsKey(e.Function.Name);
    }

    /// <summary>
    /// Determines whether the given function is a canonical function that requires special handling
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    private bool IsSpecialCanonicalFunction(DbFunctionExpression e)
    {
      return MetadataHelpers.IsCanonicalFunction(e.Function) && _canonicalFunctionHandlers.ContainsKey(e.Function.Name);
    }

    /// <summary>
    /// Default handling for functions
    /// Translates them to FunctionName(arg1, arg2, ..., argn)
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    private ISqlFragment HandleFunctionDefault(DbFunctionExpression e)
    {
      SqlBuilder result = new SqlBuilder();
      WriteFunctionName(result, e.Function);
      HandleFunctionArgumentsDefault(e, result);
      return result;
    }

    /// <summary>
    /// Default handling for functions with a given name.
    /// Translates them to functionName(arg1, arg2, ..., argn)
    /// </summary>
    /// <param name="e"></param>
    /// <param name="functionName"></param>
    /// <returns></returns>
    private ISqlFragment HandleFunctionDefaultGivenName(DbFunctionExpression e, string functionName)
    {
      SqlBuilder result = new SqlBuilder();
      result.Append(functionName);
      HandleFunctionArgumentsDefault(e, result);
      return result;
    }

    /// <summary>
    /// Default handling on function arguments
    /// Appends the list of arguments to the given result
    /// If the function is niladic it does not append anything,
    /// otherwise it appends (arg1, arg2, ..., argn)
    /// </summary>
    /// <param name="e"></param>
    /// <param name="result"></param>
    private void HandleFunctionArgumentsDefault(DbFunctionExpression e, SqlBuilder result)
    {
      bool isNiladicFunction = MetadataHelpers.TryGetValueForMetadataProperty<bool>(e.Function, "NiladicFunctionAttribute");
      if (isNiladicFunction && e.Arguments.Count > 0)
      {
        throw new InvalidOperationException("Niladic functions cannot have parameters");
      }

      if (!isNiladicFunction)
      {
        result.Append("(");
        string separator = "";
        foreach (DbExpression arg in e.Arguments)
        {
          result.Append(separator);
          result.Append(arg.Accept(this));
          separator = ", ";
        }
        result.Append(")");
      }
    }

    /// <summary>
    /// Handler for special built in functions
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    private ISqlFragment HandleSpecialBuiltInFunction(DbFunctionExpression e)
    {
      return HandleSpecialFunction(_builtInFunctionHandlers, e);
    }

    /// <summary>
    /// Handler for special canonical functions
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    private ISqlFragment HandleSpecialCanonicalFunction(DbFunctionExpression e)
    {
      return HandleSpecialFunction(_canonicalFunctionHandlers, e);
    }

    /// <summary>
    /// Dispatches the special function processing to the appropriate handler
    /// </summary>
    /// <param name="handlers"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private ISqlFragment HandleSpecialFunction(Dictionary<string, FunctionHandler> handlers, DbFunctionExpression e)
    {
      if (!handlers.ContainsKey(e.Function.Name))
        throw new InvalidOperationException("Special handling should be called only for functions in the list of special functions");

      return handlers[e.Function.Name](this, e);
    }

    /// <summary>
    /// Handles functions that are translated into TSQL operators.
    /// The given function should have one or two arguments. 
    /// Functions with one arguemnt are translated into 
    ///     op arg
    /// Functions with two arguments are translated into
    ///     arg0 op arg1
    /// Also, the arguments can be optionaly enclosed in parethesis
    /// </summary>
    /// <param name="e"></param>
    /// <param name="parenthesiseArguments">Whether the arguments should be enclosed in parethesis</param>
    /// <returns></returns>
    private ISqlFragment HandleSpecialFunctionToOperator(DbFunctionExpression e, bool parenthesiseArguments)
    {
      SqlBuilder result = new SqlBuilder();
      Debug.Assert(e.Arguments.Count > 0 && e.Arguments.Count <= 2, "There should be 1 or 2 arguments for operator");

      if (e.Arguments.Count > 1)
      {
        if (parenthesiseArguments)
        {
          result.Append("(");
        }
        result.Append(e.Arguments[0].Accept(this));
        if (parenthesiseArguments)
        {
          result.Append(")");
        }
      }
      result.Append(" ");
      Debug.Assert(_functionNameToOperatorDictionary.ContainsKey(e.Function.Name), "The function can not be mapped to an operator");
      result.Append(_functionNameToOperatorDictionary[e.Function.Name]);
      result.Append(" ");

      if (parenthesiseArguments)
      {
        result.Append("(");
      }
      result.Append(e.Arguments[e.Arguments.Count - 1].Accept(this));
      if (parenthesiseArguments)
      {
        result.Append(")");
      }
      return result;
    }


    /// <summary>
    /// <see cref="HandleSpecialFunctionToOperator"></see>
    /// </summary>
    /// <param name="sqlgen"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private static ISqlFragment HandleConcatFunction(SqlGenerator sqlgen, DbFunctionExpression e)
    {
      return sqlgen.HandleSpecialFunctionToOperator(e, false);
    }

    /// <summary>
    /// <see cref="HandleSpecialFunctionToOperator"></see>
    /// </summary>
    /// <param name="sqlgen"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private static ISqlFragment HandleCanonicalFunctionBitwise(SqlGenerator sqlgen, DbFunctionExpression e)
    {
      return sqlgen.HandleSpecialFunctionToOperator(e, true);
    }

    /// <summary>
    /// Handles special case in which datapart 'type' parameter is present. all the functions
    /// handles here have *only* the 1st parameter as datepart. datepart value is passed along
    /// the QP as string and has to be expanded as TSQL keyword.
    /// </summary>
    /// <param name="sqlgen"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private static ISqlFragment HandleDatepartDateFunction(SqlGenerator sqlgen, DbFunctionExpression e)
    {
      Debug.Assert(e.Arguments.Count > 0, "e.Arguments.Count > 0");

      DbConstantExpression constExpr = e.Arguments[0] as DbConstantExpression;
      if (null == constExpr)
      {
        throw new InvalidOperationException(String.Format("DATEPART argument to function '{0}.{1}' must be a literal string", e.Function.NamespaceName, e.Function.Name));
      }

      string datepart = constExpr.Value as string;
      if (null == datepart)
      {
        throw new InvalidOperationException(String.Format("DATEPART argument to function '{0}.{1}' must be a literal string", e.Function.NamespaceName, e.Function.Name));
      }

      SqlBuilder result = new SqlBuilder();

      //
      // check if datepart value is valid
      //
      if (!_datepartKeywords.ContainsKey(datepart))
      {
        throw new InvalidOperationException(String.Format("{0}' is not a valid value for DATEPART argument in '{1}.{2}' function", datepart, e.Function.NamespaceName, e.Function.Name));
      }

      //
      // finaly, expand the function name
      //
      sqlgen.WriteFunctionName(result, e.Function);
      result.Append("(");

      // expand the datepart literal as tsql kword
      result.Append(datepart);
      string separator = ", ";

      // expand remaining arguments
      for (int i = 1; i < e.Arguments.Count; i++)
      {
        result.Append(separator);
        result.Append(e.Arguments[i].Accept(sqlgen));
      }

      result.Append(")");

      return result;
    }

    /// <summary>
    /// DateAdd(datetime, secondsToAdd) -> DATEADD ( seconds , number,  date)
    /// </summary>
    /// <param name="sqlgen"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private static ISqlFragment HandleCanonicalFunctionDateAdd(SqlGenerator sqlgen, DbFunctionExpression e)
    {
      SqlBuilder result = new SqlBuilder();
      result.Append("DATEADD (second");

      Debug.Assert(e.Arguments.Count == 2, "Canonical datepart functions should have exactly two arguments");

      for (int i = 1; i >= 0; i--)
      {
        result.Append(", ");
        result.Append(e.Arguments[i].Accept(sqlgen));
      }

      result.Append(")");

      return result;
    }

    /// <summary>
    /// DateSubtract(datetime1, datetime2) -> DATEDIFF ( seconds , startdate , enddate ) 
    /// </summary>
    /// <param name="sqlgen"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private static ISqlFragment HandleCanonicalFunctionDateSubtract(SqlGenerator sqlgen, DbFunctionExpression e)
    {
      SqlBuilder result = new SqlBuilder();
      result.Append("DATEDIFF (second");

      Debug.Assert(e.Arguments.Count == 2, "Canonical datepart functions should have exactly two arguments");

      for (int i = 0; i < 2; i++)
      {
        result.Append(", ");
        result.Append(e.Arguments[i].Accept(sqlgen));
      }

      result.Append(")");

      return result;
    }

    /// <summary>
    /// Handler for canonical funcitons for extracting date parts. 
    /// For example:
    ///     Year(date) -> DATEPART( year, date)
    /// </summary>
    /// <param name="sqlgen"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private static ISqlFragment HandleCanonicalFunctionDatepart(SqlGenerator sqlgen, DbFunctionExpression e)
    {
      SqlBuilder result = new SqlBuilder();
      result.Append("DATEPART (");
      result.Append(e.Function.Name.ToLowerInvariant());
      result.Append(", ");

      Debug.Assert(e.Arguments.Count == 1, "Canonical datepart functions should have exactly one argument");
      result.Append(e.Arguments[0].Accept(sqlgen));

      result.Append(")");

      return result;
    }

    /// <summary>
    ///  Function rename IndexOf -> CHARINDEX
    /// </summary>
    /// <param name="sqlgen"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private static ISqlFragment HandleCanonicalFunctionIndexOf(SqlGenerator sqlgen, DbFunctionExpression e)
    {
      return sqlgen.HandleFunctionDefaultGivenName(e, "CHARINDEX");
    }

    /// <summary>
    ///  Function rename NewGuid -> NEWID
    /// </summary>
    /// <param name="sqlgen"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private static ISqlFragment HandleCanonicalFunctionNewGuid(SqlGenerator sqlgen, DbFunctionExpression e)
    {
      return sqlgen.HandleFunctionDefaultGivenName(e, "NEWID");
    }

    /// <summary>
    ///  Length(arg) -> LEN(arg + '.') - LEN('.')
    /// </summary>
    /// <param name="sqlgen"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private static ISqlFragment HandleCanonicalFunctionLength(SqlGenerator sqlgen, DbFunctionExpression e)
    {
      SqlBuilder result = new SqlBuilder();

      result.Append("LEN(");

      Debug.Assert(e.Arguments.Count == 1, "Len should have one argument");
      result.Append(e.Arguments[0].Accept(sqlgen));

      result.Append(")");
      //result.Append(" + '.') - LEN('.')");

      return result;
    }

    /// <summary>
    /// Round(numericExpression) -> Round(numericExpression, 0);
    /// </summary>
    /// <param name="sqlgen"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private static ISqlFragment HandleCanonicalFunctionRound(SqlGenerator sqlgen, DbFunctionExpression e)
    {
      SqlBuilder result = new SqlBuilder();

      result.Append("ROUND(");

      Debug.Assert(e.Arguments.Count == 1, "Round should have one argument");
      result.Append(e.Arguments[0].Accept(sqlgen));

      result.Append(", 0)");

      return result;
    }

    /// <summary>
    /// TRIM(string) -> LTRIM(RTRIM(string))
    /// </summary>
    /// <param name="sqlgen"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private static ISqlFragment HandleCanonicalFunctionTrim(SqlGenerator sqlgen, DbFunctionExpression e)
    {
      SqlBuilder result = new SqlBuilder();

      result.Append("LTRIM(RTRIM(");

      Debug.Assert(e.Arguments.Count == 1, "Trim should have one argument");
      result.Append(e.Arguments[0].Accept(sqlgen));

      result.Append("))");

      return result;
    }

    /// <summary>
    ///  Function rename ToLower -> LOWER
    /// </summary>
    /// <param name="sqlgen"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private static ISqlFragment HandleCanonicalFunctionToLower(SqlGenerator sqlgen, DbFunctionExpression e)
    {
      return sqlgen.HandleFunctionDefaultGivenName(e, "LOWER");
    }

    /// <summary>
    ///  Function rename ToUpper -> UPPER
    /// </summary>
    /// <param name="sqlgen"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private static ISqlFragment HandleCanonicalFunctionToUpper(SqlGenerator sqlgen, DbFunctionExpression e)
    {
      return sqlgen.HandleFunctionDefaultGivenName(e, "UPPER");
    }

    #endregion


    #endregion

    #region Helper methods for the DbExpressionVisitor
    /// <summary>
    /// <see cref="AddDefaultColumns"/>
    /// Add the column names from the referenced extent/join to the
    /// select statement.
    ///
    /// If the symbol is a JoinSymbol, we recursively visit all the extents,
    /// halting at real extents and JoinSymbols that have an associated SqlSelectStatement.
    ///
    /// The column names for a real extent can be derived from its type.
    /// The column names for a Join Select statement can be got from the
    /// list of columns that was created when the Join's select statement
    /// was created.
    ///
    /// We do the following for each column.
    /// <list type="number">
    /// <item>Add the SQL string for each column to the SELECT clause</item>
    /// <item>Add the column to the list of columns - so that it can
    /// become part of the "type" of a JoinSymbol</item>
    /// <item>Check if the column name collides with a previous column added
    /// to the same select statement.  Flag both the columns for renaming if true.</item>
    /// <item>Add the column to a name lookup dictionary for collision detection.</item>
    /// </list>
    /// </summary>
    /// <param name="selectStatement">The select statement that started off as SELECT *</param>
    /// <param name="symbol">The symbol containing the type information for
    /// the columns to be added.</param>
    /// <param name="columnList">Columns that have been added to the Select statement.
    /// This is created in <see cref="AddDefaultColumns"/>.</param>
    /// <param name="columnDictionary">A dictionary of the columns above.</param>
    /// <param name="separator">Comma or nothing, depending on whether the SELECT
    /// clause is empty.</param>
    void AddColumns(SqlSelectStatement selectStatement, Symbol symbol,
        List<Symbol> columnList, Dictionary<string, Symbol> columnDictionary, ref string separator)
    {
      JoinSymbol joinSymbol = symbol as JoinSymbol;
      if (joinSymbol != null)
      {
        if (!joinSymbol.IsNestedJoin)
        {
          // Recurse if the join symbol is a collection of flattened extents
          foreach (Symbol sym in joinSymbol.ExtentList)
          {
            // if sym is ScalarType means we are at base case in the
            // recursion and there are not columns to add, just skip
            if (MetadataHelpers.IsPrimitiveType(sym.Type))
            {
              continue;
            }

            AddColumns(selectStatement, sym, columnList, columnDictionary, ref separator);
          }
        }
        else
        {
          foreach (Symbol joinColumn in joinSymbol.ColumnList)
          {
            // we write tableName.columnName
            // rather than tableName.columnName as alias
            // since the column name is unique (by the way we generate new column names)
            //
            // We use the symbols for both the table and the column,
            // since they are subject to renaming.
            selectStatement.Select.Append(separator);
            selectStatement.Select.Append(symbol);
            selectStatement.Select.Append(".");
            selectStatement.Select.Append(joinColumn);

            // check for name collisions.  If there is,
            // flag both the colliding symbols.
            if (columnDictionary.ContainsKey(joinColumn.Name))
            {
              columnDictionary[joinColumn.Name].NeedsRenaming = true; // the original symbol
              joinColumn.NeedsRenaming = true; // the current symbol.
            }
            else
            {
              columnDictionary[joinColumn.Name] = joinColumn;
            }

            columnList.Add(joinColumn);

            separator = ", ";
          }
        }
      }
      else
      {
        // This is a non-join extent/select statement, and the CQT type has
        // the relevant column information.

        // The type could be a record type(e.g. Project(...),
        // or an entity type ( e.g. EntityExpression(...)
        // so, we check whether it is a structuralType.

        // Consider an expression of the form J(a, b=P(E))
        // The inner P(E) would have been translated to a SQL statement
        // We should not use the raw names from the type, but the equivalent
        // symbols (they are present in symbol.Columns) if they exist.
        //
        // We add the new columns to the symbol's columns if they do
        // not already exist.
        //

        foreach (EdmProperty property in MetadataHelpers.GetProperties(symbol.Type))
        {
          string recordMemberName = property.Name;
          // Since all renaming happens in the second phase
          // we lose nothing by setting the next column name index to 0
          // many times.
          allColumnNames[recordMemberName] = 0;

          // Create a new symbol/reuse existing symbol for the column
          Symbol columnSymbol;
          if (!symbol.Columns.TryGetValue(recordMemberName, out columnSymbol))
          {
            // we do not care about the types of columns, so we pass null
            // when construction the symbol.
            columnSymbol = new Symbol(recordMemberName, null);
            symbol.Columns.Add(recordMemberName, columnSymbol);
          }

          selectStatement.Select.Append(separator);
          selectStatement.Select.Append(symbol);
          selectStatement.Select.Append(".");

          // We use the actual name before the "AS", the new name goes
          // after the AS.
          selectStatement.Select.Append(QuoteIdentifier(recordMemberName));

          selectStatement.Select.Append(" AS ");
          selectStatement.Select.Append(columnSymbol);

          // Check for column name collisions.
          if (columnDictionary.ContainsKey(recordMemberName))
          {
            columnDictionary[recordMemberName].NeedsRenaming = true;
            columnSymbol.NeedsRenaming = true;
          }
          else
          {
            columnDictionary[recordMemberName] = symbol.Columns[recordMemberName];
          }

          columnList.Add(columnSymbol);

          separator = ", ";
        }
      }
    }

    /// <summary>
    /// Expands Select * to "select the_list_of_columns"
    /// If the columns are taken from an extent, they are written as
    /// {original_column_name AS Symbol(original_column)} to allow renaming.
    ///
    /// If the columns are taken from a Join, they are written as just
    /// {original_column_name}, since there cannot be a name collision.
    ///
    /// We concatenate the columns from each of the inputs to the select statement.
    /// Since the inputs may be joins that are flattened, we need to recurse.
    /// The inputs are inferred from the symbols in FromExtents.
    /// </summary>
    /// <param name="selectStatement"></param>
    /// <returns></returns>
    List<Symbol> AddDefaultColumns(SqlSelectStatement selectStatement)
    {
      // This is the list of columns added in this select statement
      // This forms the "type" of the Select statement, if it has to
      // be expanded in another SELECT *
      List<Symbol> columnList = new List<Symbol>();

      // A lookup for the previous set of columns to aid column name
      // collision detection.
      Dictionary<string, Symbol> columnDictionary = new Dictionary<string, Symbol>(StringComparer.OrdinalIgnoreCase);

      string separator = "";
      // The Select should usually be empty before we are called,
      // but we do not mind if it is not.
      if (!selectStatement.Select.IsEmpty)
      {
        separator = ", ";
      }

      foreach (Symbol symbol in selectStatement.FromExtents)
      {
        AddColumns(selectStatement, symbol, columnList, columnDictionary, ref separator);
      }

      return columnList;
    }

    /// <summary>
    /// <see cref="AddFromSymbol(SqlSelectStatement, string, Symbol, bool)"/>
    /// </summary>
    /// <param name="selectStatement"></param>
    /// <param name="inputVarName"></param>
    /// <param name="fromSymbol"></param>
    void AddFromSymbol(SqlSelectStatement selectStatement, string inputVarName, Symbol fromSymbol)
    {
      AddFromSymbol(selectStatement, inputVarName, fromSymbol, true);
    }

    /// <summary>
    /// This method is called after the input to a relational node is visited.
    /// <see cref="Visit(DbProjectExpression)"/> and <see cref="ProcessJoinInputResult"/>
    /// There are 2 scenarios
    /// <list type="number">
    /// <item>The fromSymbol is new i.e. the select statement has just been
    /// created, or a join extent has been added.</item>
    /// <item>The fromSymbol is old i.e. we are reusing a select statement.</item>
    /// </list>
    ///
    /// If we are not reusing the select statement, we have to complete the
    /// FROM clause with the alias
    /// <code>
    /// -- if the input was an extent
    /// FROM = [SchemaName].[TableName]
    /// -- if the input was a Project
    /// FROM = (SELECT ... FROM ... WHERE ...)
    /// </code>
    ///
    /// These become
    /// <code>
    /// -- if the input was an extent
    /// FROM = [SchemaName].[TableName] AS alias
    /// -- if the input was a Project
    /// FROM = (SELECT ... FROM ... WHERE ...) AS alias
    /// </code>
    /// and look like valid FROM clauses.
    ///
    /// Finally, we have to add the alias to the global list of aliases used,
    /// and also to the current symbol table.
    /// </summary>
    /// <param name="selectStatement"></param>
    /// <param name="inputVarName">The alias to be used.</param>
    /// <param name="fromSymbol"></param>
    /// <param name="addToSymbolTable"></param>
    void AddFromSymbol(SqlSelectStatement selectStatement, string inputVarName, Symbol fromSymbol, bool addToSymbolTable)
    {
      // the first check is true if this is a new statement
      // the second check is true if we are in a join - we do not
      // check if we are in a join context.
      // We do not want to add "AS alias" if it has been done already
      // e.g. when we are reusing the Sql statement.
      if (selectStatement.FromExtents.Count == 0 || fromSymbol != selectStatement.FromExtents[0])
      {
        selectStatement.FromExtents.Add(fromSymbol);
        selectStatement.From.Append(" AS ");
        selectStatement.From.Append(fromSymbol);

        // We have this inside the if statement, since
        // we only want to add extents that are actually used.
        allExtentNames[fromSymbol.Name] = 0;
      }

      if (addToSymbolTable)
      {
        symbolTable.Add(inputVarName, fromSymbol);
      }
    }

    /// <summary>
    /// Translates a list of SortClauses.
    /// Used in the translation of OrderBy 
    /// </summary>
    /// <param name="orderByClause">The SqlBuilder to which the sort keys should be appended</param>
    /// <param name="sortKeys"></param>
    void AddSortKeys(SqlBuilder orderByClause, IList<DbSortClause> sortKeys)
    {
      string separator = "";
      foreach (DbSortClause sortClause in sortKeys)
      {
        orderByClause.Append(separator);
        orderByClause.Append(sortClause.Expression.Accept(this));
        Debug.Assert(sortClause.Collation != null);
        if (!String.IsNullOrEmpty(sortClause.Collation))
        {
          orderByClause.Append(" COLLATE ");
          orderByClause.Append(sortClause.Collation);
        }

        orderByClause.Append(sortClause.Ascending ? " ASC" : " DESC");

        separator = ", ";
      }
    }

    /// <summary>
    /// <see cref="CreateNewSelectStatement(SqlSelectStatement oldStatement, string inputVarName, TypeUsage inputVarType, bool finalizeOldStatement, out Symbol fromSymbol) "/>
    /// </summary>
    /// <param name="oldStatement"></param>
    /// <param name="inputVarName"></param>
    /// <param name="inputVarType"></param>
    /// <param name="fromSymbol"></param>
    /// <returns>A new select statement, with the old one as the from clause.</returns>
    SqlSelectStatement CreateNewSelectStatement(SqlSelectStatement oldStatement,
        string inputVarName, TypeUsage inputVarType, out Symbol fromSymbol)
    {
      return CreateNewSelectStatement(oldStatement, inputVarName, inputVarType, true, out fromSymbol);
    }


    /// <summary>
    /// This is called after a relational node's input has been visited, and the
    /// input's sql statement cannot be reused.  <see cref="Visit(DbProjectExpression)"/>
    ///
    /// When the input's sql statement cannot be reused, we create a new sql
    /// statement, with the old one as the from clause of the new statement.
    ///
    /// The old statement must be completed i.e. if it has an empty select list,
    /// the list of columns must be projected out.
    ///
    /// If the old statement being completed has a join symbol as its from extent,
    /// the new statement must have a clone of the join symbol as its extent.
    /// We cannot reuse the old symbol, but the new select statement must behave
    /// as though it is working over the "join" record.
    /// </summary>
    /// <param name="oldStatement"></param>
    /// <param name="inputVarName"></param>
    /// <param name="inputVarType"></param>
    /// <param name="finalizeOldStatement"></param>
    /// <param name="fromSymbol"></param>
    /// <returns>A new select statement, with the old one as the from clause.</returns>
    SqlSelectStatement CreateNewSelectStatement(SqlSelectStatement oldStatement,
        string inputVarName, TypeUsage inputVarType, bool finalizeOldStatement, out Symbol fromSymbol)
    {
      fromSymbol = null;

      // Finalize the old statement
      if (finalizeOldStatement && oldStatement.Select.IsEmpty)
      {
        List<Symbol> columns = AddDefaultColumns(oldStatement);

        // Thid could not have been called from a join node.
        Debug.Assert(oldStatement.FromExtents.Count == 1);

        // if the oldStatement has a join as its input, ...
        // clone the join symbol, so that we "reuse" the
        // join symbol.  Normally, we create a new symbol - see the next block
        // of code.
        JoinSymbol oldJoinSymbol = oldStatement.FromExtents[0] as JoinSymbol;
        if (oldJoinSymbol != null)
        {
          // Note: oldStatement.FromExtents will not do, since it might
          // just be an alias of joinSymbol, and we want an actual JoinSymbol.
          JoinSymbol newJoinSymbol = new JoinSymbol(inputVarName, inputVarType, oldJoinSymbol.ExtentList);
          // This indicates that the oldStatement is a blocking scope
          // i.e. it hides/renames extent columns
          newJoinSymbol.IsNestedJoin = true;
          newJoinSymbol.ColumnList = columns;
          newJoinSymbol.FlattenedExtentList = oldJoinSymbol.FlattenedExtentList;

          fromSymbol = newJoinSymbol;
        }
      }

      if (fromSymbol == null)
      {
        // This is just a simple extent/SqlSelectStatement,
        // and we can get the column list from the type.
        fromSymbol = new Symbol(inputVarName, inputVarType);
      }

      // Observe that the following looks like the body of Visit(ExtentExpression).
      SqlSelectStatement selectStatement = new SqlSelectStatement();
      selectStatement.From.Append("( ");
      selectStatement.From.Append(oldStatement);
      selectStatement.From.AppendLine();
      selectStatement.From.Append(") ");


      return selectStatement;
    }


    /// <summary>
    /// Before we embed a string literal in a SQL string, we should
    /// convert all ' to '', and enclose the whole string in single quotes.
    /// </summary>
    /// <param name="s"></param>
    /// <param name="isUnicode"></param>
    /// <returns>The escaped sql string.</returns>
    private string EscapeSingleQuote(string s, bool isUnicode)
    {
      return "'" + s.Replace("'", "''") + "'";
    }

    /// <summary>
    /// Returns the sql primitive/native type name. 
    /// It will include size, precision or scale depending on type information present in the 
    /// type facets
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    private string GetSqlPrimitiveType(TypeUsage type)
    {
      PrimitiveType primitiveType = MetadataHelpers.GetEdmType<PrimitiveType>(type);

      string typeName = primitiveType.Name;
      bool isUnicode = true;
      bool isFixedLength = false;
      int maxLength = 0;
      string length = "max";
      bool preserveSeconds = true;
      byte decimalPrecision = 0;
      byte decimalScale = 0;

      switch (primitiveType.PrimitiveTypeKind)
      {
        case PrimitiveTypeKind.Binary:
          maxLength = MetadataHelpers.GetFacetValueOrDefault<int>(type, MetadataHelpers.MaxLengthFacetName, MetadataHelpers.BinaryMaxMaxLength);
          if (maxLength == MetadataHelpers.BinaryMaxMaxLength)
          {
            length = "max";
          }
          else
          {
            length = maxLength.ToString(CultureInfo.InvariantCulture);
          }
          isFixedLength = MetadataHelpers.GetFacetValueOrDefault<bool>(type, MetadataHelpers.FixedLengthFacetName, false);
          typeName = (isFixedLength ? "binary(" : "varbinary(") + length + ")";
          break;

        case PrimitiveTypeKind.String:
          // Question: How do we handle ntext?
          isUnicode = MetadataHelpers.GetFacetValueOrDefault<bool>(type, MetadataHelpers.UnicodeFacetName, true);
          isFixedLength = MetadataHelpers.GetFacetValueOrDefault<bool>(type, MetadataHelpers.FixedLengthFacetName, false);
          maxLength = MetadataHelpers.GetFacetValueOrDefault<int>(type, MetadataHelpers.MaxLengthFacetName, Int32.MinValue);
          if (maxLength == Int32.MinValue)
          {
            length = "max";
          }
          else
          {
            length = maxLength.ToString(CultureInfo.InvariantCulture);
          }
          if (isUnicode && !isFixedLength && maxLength > 4000)
            length = "max";
          if (!isUnicode && !isFixedLength && maxLength > 8000)
            length = "max";
          if (isFixedLength)
          {
            typeName = (isUnicode ? "nchar(" : "char(") + length + ")";
          }
          else
          {
            typeName = (isUnicode ? "nvarchar(" : "varchar(") + length + ")";
          }
          break;

        case PrimitiveTypeKind.DateTime:
          preserveSeconds = MetadataHelpers.GetFacetValueOrDefault<bool>(type, MetadataHelpers.PreserveSecondsFacetName, false);
          typeName = preserveSeconds ? "datetime" : "smalldatetime";
          break;

        case PrimitiveTypeKind.Decimal:
          decimalPrecision = MetadataHelpers.GetFacetValueOrDefault<byte>(type, MetadataHelpers.PrecisionFacetName, 18);
          Debug.Assert(decimalPrecision > 0, "decimal precision must be greater than zero");
          decimalScale = MetadataHelpers.GetFacetValueOrDefault<byte>(type, MetadataHelpers.ScaleFacetName, 0);
          Debug.Assert(decimalPrecision >= decimalScale, "decimalPrecision must be greater or equal to decimalScale");
          Debug.Assert(decimalPrecision <= 53, "decimalPrecision must be less than or equal to 53");
          typeName = typeName + "(" + decimalPrecision + "," + decimalScale + ")";
          break;

        case PrimitiveTypeKind.Int32:
          typeName = "int";
          break;

        case PrimitiveTypeKind.Int64:
          typeName = "bigint";
          break;

        case PrimitiveTypeKind.Int16:
          typeName = "smallint";
          break;

        case PrimitiveTypeKind.Byte:
          typeName = "tinyint";
          break;

        case PrimitiveTypeKind.Boolean:
          typeName = "bit";
          break;

        case PrimitiveTypeKind.Single:
          typeName = "real";
          break;

        case PrimitiveTypeKind.Double:
          typeName = "float";
          break;

        case PrimitiveTypeKind.Guid:
          typeName = "uniqueidentifier";
          break;

        default:
          throw new NotSupportedException("Unsupported EdmType: " + primitiveType.PrimitiveTypeKind);
      }

      return typeName;
    }

    /// <summary>
    /// Handles the expression represending DbLimitExpression.Limit and DbSkipExpression.Count.
    /// If it is a constant expression, it simply does to string thus avoiding casting it to the specific value
    /// (which would be done if <see cref="Visit(DbConstantExpression)"/> is called)
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    private ISqlFragment HandaleCountExpression(DbExpression e)
    {
      ISqlFragment result;


      if (e.ExpressionKind == DbExpressionKind.Constant)
      {
        //For constant expression we should not cast the value, 
        // thus we don't go throught the default DbConstantExpression handling
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.Append(((DbConstantExpression)e).Value.ToString());
        result = sqlBuilder;
      }
      else
      {
        result = e.Accept(this);
      }

      return result;
    }

    /// <summary>

    /// This is used to determine if a particular expression is an Apply operation.
    /// This is only the case when the DbExpressionKind is CrossApply or OuterApply.
    /// </summary>

    /// <param name="e"></param>
    /// <returns></returns>
    bool IsApplyExpression(DbExpression e)
    {
      return (DbExpressionKind.CrossApply == e.ExpressionKind || DbExpressionKind.OuterApply == e.ExpressionKind);
    }

    /// <summary>
    /// This is used to determine if a particular expression is a Join operation.
    /// This is true for DbCrossJoinExpression and DbJoinExpression, the
    /// latter of which may have one of several different ExpressionKinds.
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    bool IsJoinExpression(DbExpression e)
    {
      return (DbExpressionKind.CrossJoin == e.ExpressionKind ||
              DbExpressionKind.FullOuterJoin == e.ExpressionKind ||
              DbExpressionKind.InnerJoin == e.ExpressionKind ||
              DbExpressionKind.LeftOuterJoin == e.ExpressionKind);
    }

    /// <summary>
    /// This is used to determine if a calling expression needs to place
    /// round brackets around the translation of the expression e.
    ///
    /// Constants, parameters and properties do not require brackets,
    /// everything else does.
    /// </summary>
    /// <param name="e"></param>
    /// <returns>true, if the expression needs brackets </returns>
    bool IsComplexExpression(DbExpression e)
    {
      switch (e.ExpressionKind)
      {
        case DbExpressionKind.Constant:
        case DbExpressionKind.ParameterReference:
        case DbExpressionKind.Property:
          return false;

        default:
          return true;
      }
    }

    /// <summary>
    /// Determine if the owner expression can add its unique sql to the input's
    /// SqlSelectStatement
    /// </summary>
    /// <param name="result">The SqlSelectStatement of the input to the relational node.</param>
    /// <param name="expressionKind">The kind of the expression node(not the input's)</param>
    /// <returns></returns>
    bool IsCompatible(SqlSelectStatement result, DbExpressionKind expressionKind)
    {
      switch (expressionKind)
      {
        case DbExpressionKind.Distinct:
          return result.Top == null
            // The projection after distinct may not project all 
            // columns used in the Order By
              && result.OrderBy.IsEmpty;

        case DbExpressionKind.Filter:
          return result.Select.IsEmpty
                  && result.Where.IsEmpty
                  && result.GroupBy.IsEmpty
                  && result.Top == null;

        case DbExpressionKind.GroupBy:
          return result.Select.IsEmpty
                  && result.GroupBy.IsEmpty
                  && result.OrderBy.IsEmpty
                  && result.Top == null;

        case DbExpressionKind.Limit:
        case DbExpressionKind.Element:
          return result.Top == null;

        case DbExpressionKind.Project:
          return result.Select.IsEmpty
                  && result.GroupBy.IsEmpty;

        case DbExpressionKind.Skip:
          return result.Select.IsEmpty
                  && result.GroupBy.IsEmpty
                  && result.OrderBy.IsEmpty
                  && !result.IsDistinct;

        case DbExpressionKind.Sort:
          return result.Select.IsEmpty
                  && result.GroupBy.IsEmpty
                  && result.OrderBy.IsEmpty;

        default:
          Debug.Assert(false);
          throw new InvalidOperationException();
      }

    }

    /// <summary>
    /// We use the normal box quotes for SQL server.  We do not deal with ANSI quotes
    /// i.e. double quotes.
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    internal static string QuoteIdentifier(string name)
    {
      Debug.Assert(!String.IsNullOrEmpty(name));
      // We assume that the names are not quoted to begin with.
      return "[" + name.Replace("]", "]]") + "]";
    }

    /// <summary>
    /// Simply calls <see cref="VisitExpressionEnsureSqlStatement(DbExpression, bool)"/>
    /// with addDefaultColumns set to true
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    SqlSelectStatement VisitExpressionEnsureSqlStatement(DbExpression e)
    {
      return VisitExpressionEnsureSqlStatement(e, true);
    }

    /// <summary>
    /// This is called from <see cref="GenerateSql(DbQueryCommandTree)"/> and nodes which require a
    /// select statement as an argument e.g. <see cref="Visit(DbIsEmptyExpression)"/>,
    /// <see cref="Visit(DbUnionAllExpression)"/>.
    ///
    /// SqlGenerator needs its child to have a proper alias if the child is
    /// just an extent or a join.
    ///
    /// The normal relational nodes result in complete valid SQL statements.
    /// For the rest, we need to treat them as there was a dummy
    /// <code>
    /// -- originally {expression}
    /// -- change that to
    /// SELECT *
    /// FROM {expression} as c
    /// </code>
    /// 
    /// DbLimitExpression needs to start the statement but not add the default columns
    /// </summary>
    /// <param name="e"></param>
    /// <param name="addDefaultColumns"></param>
    /// <returns></returns>
    SqlSelectStatement VisitExpressionEnsureSqlStatement(DbExpression e, bool addDefaultColumns)
    {
      Debug.Assert(MetadataHelpers.IsCollectionType(e.ResultType));

      SqlSelectStatement result;
      switch (e.ExpressionKind)
      {
        case DbExpressionKind.Project:
        case DbExpressionKind.Filter:
        case DbExpressionKind.GroupBy:
        case DbExpressionKind.Sort:
          result = e.Accept(this) as SqlSelectStatement;
          break;

        default:
          Symbol fromSymbol;
          string inputVarName = "c";  // any name will do - this is my random choice.
          symbolTable.EnterScope();

          TypeUsage type = null;
          switch (e.ExpressionKind)
          {
            case DbExpressionKind.Scan:
            case DbExpressionKind.CrossJoin:
            case DbExpressionKind.FullOuterJoin:
            case DbExpressionKind.InnerJoin:
            case DbExpressionKind.LeftOuterJoin:
            case DbExpressionKind.CrossApply:
            case DbExpressionKind.OuterApply:
              type = MetadataHelpers.GetElementTypeUsage(e.ResultType);
              break;

            default:
              Debug.Assert(MetadataHelpers.IsCollectionType(e.ResultType));
              type = MetadataHelpers.GetEdmType<CollectionType>(e.ResultType).TypeUsage;
              break;
          }

          result = VisitInputExpression(e, inputVarName, type, out fromSymbol);
          AddFromSymbol(result, inputVarName, fromSymbol);
          symbolTable.ExitScope();
          break;
      }

      if (addDefaultColumns && result.Select.IsEmpty)
      {
        AddDefaultColumns(result);
      }

      return result;
    }

    /// <summary>
    /// This method is called by <see cref="Visit(DbFilterExpression)"/> and
    /// <see cref="Visit(DbQuantifierExpression)"/>
    ///
    /// </summary>
    /// <param name="input"></param>
    /// <param name="predicate"></param>
    /// <param name="negatePredicate">This is passed from <see cref="Visit(DbQuantifierExpression)"/>
    /// in the All(...) case.</param>
    /// <returns></returns>
    SqlSelectStatement VisitFilterExpression(DbExpressionBinding input, DbExpression predicate, bool negatePredicate)
    {
      Symbol fromSymbol;
      SqlSelectStatement result = VisitInputExpression(input.Expression,
          input.VariableName, input.VariableType, out fromSymbol);

      // Filter is compatible with OrderBy
      // but not with Project, another Filter or GroupBy
      if (!IsCompatible(result, DbExpressionKind.Filter))
      {
        result = CreateNewSelectStatement(result, input.VariableName, input.VariableType, out fromSymbol);
      }

      selectStatementStack.Push(result);
      symbolTable.EnterScope();

      AddFromSymbol(result, input.VariableName, fromSymbol);

      if (negatePredicate)
      {
        result.Where.Append("NOT (");
      }
      result.Where.Append(predicate.Accept(this));
      if (negatePredicate)
      {
        result.Where.Append(")");
      }

      symbolTable.ExitScope();
      selectStatementStack.Pop();

      return result;
    }

    /// <summary>
    /// If the sql fragment for an input expression is not a SqlSelect statement
    /// or other acceptable form (e.g. an extent as a SqlBuilder), we need
    /// to wrap it in a form acceptable in a FROM clause.  These are
    /// primarily the
    /// <list type="bullet">
    /// <item>The set operation expressions - union all, intersect, except</item>
    /// <item>TVFs, which are conceptually similar to tables</item>
    /// </list>
    /// </summary>
    /// <param name="result"></param>
    /// <param name="sqlFragment"></param>
    /// <param name="expressionKind"></param>
    void WrapNonQueryExtent(SqlSelectStatement result, ISqlFragment sqlFragment, DbExpressionKind expressionKind)
    {
      switch (expressionKind)
      {
        case DbExpressionKind.Function:
          // TVF
          result.From.Append(sqlFragment);
          break;

        default:
          result.From.Append(" (");
          result.From.Append(sqlFragment);
          result.From.Append(")");
          break;
      }
    }

    /// <summary>
    /// Is this a builtin function (ie) does it have the builtinAttribute specified?
    /// </summary>
    /// <param name="function"></param>
    /// <returns></returns>
    private static bool IsBuiltinFunction(EdmFunction function)
    {
      return MetadataHelpers.TryGetValueForMetadataProperty<bool>(function, "BuiltInAttribute");
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="function"></param>
    /// <param name="result"></param>
    void WriteFunctionName(SqlBuilder result, EdmFunction function)
    {

      string storeFunctionName = MetadataHelpers.TryGetValueForMetadataProperty<string>(function, "StoreFunctionNameAttribute");

      if (string.IsNullOrEmpty(storeFunctionName))
      {
        storeFunctionName = function.Name;
      }

      // If the function is a builtin (ie) the BuiltIn attribute has been
      // specified, then, the function name should not be quoted; additionally,
      // no namespace should be used.
      if (IsBuiltinFunction(function))
      {
        if (function.NamespaceName == "Edm")
        {
          switch (storeFunctionName.ToUpperInvariant())
          {
            default:
              result.Append(storeFunctionName);
              break;
          }

        }
        else
        {
          result.Append(storeFunctionName);
        }

      }
      else
      {
        // Should we actually support this?
        result.Append(QuoteIdentifier((string)function.MetadataProperties["Schema"].Value ?? "dbo"));
        result.Append(".");
        result.Append(QuoteIdentifier(storeFunctionName));
      }
    }

    static string ByteArrayToBinaryString(Byte[] binaryArray)
    {
      StringBuilder sb = new StringBuilder(binaryArray.Length * 2);
      for (int i = 0; i < binaryArray.Length; i++)
      {
        sb.Append(hexDigits[(binaryArray[i] & 0xF0) >> 4]).Append(hexDigits[binaryArray[i] & 0x0F]);
      }
      return sb.ToString();
    }

    /// <summary>
    /// Helper method for the Group By visitor
    /// Returns true if at least one of the aggregates in the given list
    /// has an argument that is not a <see cref="DbPropertyExpression"/> 
    /// over <see cref="DbVariableReferenceExpression"/>
    /// </summary>
    /// <param name="aggregates"></param>


    /// <returns></returns>
    static bool NeedsInnerQuery(IList<DbAggregate> aggregates)
    {


      foreach (DbAggregate aggregate in aggregates)
      {
        Debug.Assert(aggregate.Arguments.Count == 1);
        if (!IsPropertyOverVarRef(aggregate.Arguments[0]))
        {
          return true;
        }
      }
      return false;
    }

    /// <summary>
    /// Determines whether the given expression is a <see cref="DbPropertyExpression"/> 
    /// over <see cref="DbVariableReferenceExpression"/>
    /// </summary>
    /// <param name="expression"></param>

    /// <returns></returns>
    static bool IsPropertyOverVarRef(DbExpression expression)
    {

      DbPropertyExpression propertyExpression = expression as DbPropertyExpression;
      if (propertyExpression == null)


      {

        return false;
      }







      DbVariableReferenceExpression varRefExpression = propertyExpression.Instance as DbVariableReferenceExpression;
      if (varRefExpression == null)
      {


        return false;
      }


      return true;
    }






    #endregion
  }


}

Changes to System.Data.SQLite.Linq/SQLiteProviderServices.cs.

336
337
338
339
340
341
342



343
344
345
346
347
348
349
350
...
353
354
355
356
357
358
359





360
361
362
363
364
365
366
367
368
369
370
      using (SQLiteCommand cmd = cnn.CreateCommand())
      using (DataTable source = new DataTable())
      {
        sql.AppendFormat(CultureInfo.InvariantCulture, "CREATE TEMP TABLE {0} (", builder.QuoteIdentifier(dest));
        string separator = String.Empty;
        foreach (DataColumn dc in table.Columns)
        {



          sql.AppendFormat(CultureInfo.InvariantCulture, "{2}{0} {1}", builder.QuoteIdentifier(dc.ColumnName), SQLiteConvert.DbTypeToTypeName(SQLiteConvert.TypeToDbType(dc.DataType)), separator);
          separator = ", ";
        }
        sql.Append(")");

        cmd.CommandText = sql.ToString();
        cmd.ExecuteNonQuery();

................................................................................
        {
          builder.DataAdapter = adp;

          adp.Fill(source);

          foreach (DataRow row in table.Rows)
          {





            source.Rows.Add(row.ItemArray);
          }
          adp.Update(source);
        }
      }
    }

    #endregion
  }
}








>
>
>
|







 







>
>
>
>
>
|










336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
...
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
      using (SQLiteCommand cmd = cnn.CreateCommand())
      using (DataTable source = new DataTable())
      {
        sql.AppendFormat(CultureInfo.InvariantCulture, "CREATE TEMP TABLE {0} (", builder.QuoteIdentifier(dest));
        string separator = String.Empty;
        foreach (DataColumn dc in table.Columns)
        {
          DbType dbtypeName = SQLiteConvert.TypeToDbType(dc.DataType);
          string typeName = SQLiteConvert.DbTypeToTypeName(dbtypeName);

          sql.AppendFormat(CultureInfo.InvariantCulture, "{2}{0} {1}", builder.QuoteIdentifier(dc.ColumnName), typeName, separator);
          separator = ", ";
        }
        sql.Append(")");

        cmd.CommandText = sql.ToString();
        cmd.ExecuteNonQuery();

................................................................................
        {
          builder.DataAdapter = adp;

          adp.Fill(source);

          foreach (DataRow row in table.Rows)
          {
            object[] arr = row.ItemArray;

            for (int n = 0; n < arr.Length; n++)
              if (arr[n] is string) arr[n] = ((string)arr[n]).ToLower();

            source.Rows.Add(arr);
          }
          adp.Update(source);
        }
      }
    }

    #endregion
  }
}

Changes to System.Data.SQLite.Linq/System.Data.SQLite.Linq.csproj.

39
40
41
42
43
44
45




46
47
48
49
50
51
52
..
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    <Reference Include="System" />
    <Reference Include="System.Core">
      <RequiredTargetFramework>3.5</RequiredTargetFramework>
    </Reference>
    <Reference Include="System.Data" />
    <Reference Include="System.Data.Entity">
      <RequiredTargetFramework>3.5</RequiredTargetFramework>




    </Reference>
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="AssemblyInfo.cs" />
    <Compile Include="Properties\Resources.Designer.cs">
      <AutoGen>True</AutoGen>
................................................................................
    <Compile Include="SQL Generation\SymbolPair.cs" />
    <Compile Include="SQL Generation\SymbolTable.cs" />
    <Compile Include="SQL Generation\TopClause.cs" />
    <Compile Include="SQLiteProviderManifest.cs" />
    <Compile Include="SQLiteProviderServices.cs" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\System.Data.SQLite\System.Data.SQLite - Full.csproj">
      <Project>{AC139952-261A-4463-B6FA-AEBC25283A66}</Project>
      <Name>System.Data.SQLite - Full</Name>
      <Private>False</Private>
    </ProjectReference>
  </ItemGroup>
  <ItemGroup>
    <None Include="Resources\Common.ConceptualSchemaDefinition.csdl" />
    <None Include="Resources\Common.ProviderManifest.xsd" />
    <EmbeddedResource Include="Resources\SQLiteProviderServices.StoreSchemaDefinition.ssdl" />
    <EmbeddedResource Include="Resources\SQLiteProviderServices.StoreSchemaMapping.msl" />
    <None Include="Resources\System.Data.Resources.CSDLSchema.xsd" />
    <None Include="Resources\System.Data.Resources.CSMSL.xsd" />
    <None Include="Resources\System.Data.Resources.EntityStoreSchemaGenerator.xsd" />







>
>
>
>







 







<
<
<
<
<
<
<







39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
..
69
70
71
72
73
74
75







76
77
78
79
80
81
82
    <Reference Include="System" />
    <Reference Include="System.Core">
      <RequiredTargetFramework>3.5</RequiredTargetFramework>
    </Reference>
    <Reference Include="System.Data" />
    <Reference Include="System.Data.Entity">
      <RequiredTargetFramework>3.5</RequiredTargetFramework>
    </Reference>
    <Reference Include="System.Data.SQLite, Version=1.0.52.0, Culture=neutral, PublicKeyToken=1fdb50b1b62b4c84, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <Private>False</Private>
    </Reference>
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="AssemblyInfo.cs" />
    <Compile Include="Properties\Resources.Designer.cs">
      <AutoGen>True</AutoGen>
................................................................................
    <Compile Include="SQL Generation\SymbolPair.cs" />
    <Compile Include="SQL Generation\SymbolTable.cs" />
    <Compile Include="SQL Generation\TopClause.cs" />
    <Compile Include="SQLiteProviderManifest.cs" />
    <Compile Include="SQLiteProviderServices.cs" />
  </ItemGroup>
  <ItemGroup>







    <None Include="Resources\Common.ConceptualSchemaDefinition.csdl" />
    <None Include="Resources\Common.ProviderManifest.xsd" />
    <EmbeddedResource Include="Resources\SQLiteProviderServices.StoreSchemaDefinition.ssdl" />
    <EmbeddedResource Include="Resources\SQLiteProviderServices.StoreSchemaMapping.msl" />
    <None Include="Resources\System.Data.Resources.CSDLSchema.xsd" />
    <None Include="Resources\System.Data.Resources.CSMSL.xsd" />
    <None Include="Resources\System.Data.Resources.EntityStoreSchemaGenerator.xsd" />

Changes to System.Data.SQLite/AssemblyInfo.cs.

44
45
46
47
48
49
50
51
52
53
54
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers 
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.52.0")]
#if !PLATFORM_COMPACTFRAMEWORK
[assembly: AssemblyFileVersion("1.0.52.0")]
#endif







|

|

44
45
46
47
48
49
50
51
52
53
54
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers 
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.53.0")]
#if !PLATFORM_COMPACTFRAMEWORK
[assembly: AssemblyFileVersion("1.0.53.0")]
#endif

Changes to System.Data.SQLite/MetaDataCollections.xml.

56
57
58
59
60
61
62





63
    <NumberOfIdentifierParts>4</NumberOfIdentifierParts>
  </MetaDataCollections>
  <MetaDataCollections>
    <CollectionName>ForeignKeys</CollectionName>
    <NumberOfRestrictions>4</NumberOfRestrictions>
    <NumberOfIdentifierParts>3</NumberOfIdentifierParts>
  </MetaDataCollections>





</DocumentElement>







>
>
>
>
>

56
57
58
59
60
61
62
63
64
65
66
67
68
    <NumberOfIdentifierParts>4</NumberOfIdentifierParts>
  </MetaDataCollections>
  <MetaDataCollections>
    <CollectionName>ForeignKeys</CollectionName>
    <NumberOfRestrictions>4</NumberOfRestrictions>
    <NumberOfIdentifierParts>3</NumberOfIdentifierParts>
  </MetaDataCollections>
  <MetaDataCollections>
    <CollectionName>Triggers</CollectionName>
    <NumberOfRestrictions>4</NumberOfRestrictions>
    <NumberOfIndentifierParts>3</NumberOfIndentifierParts>
  </MetaDataCollections>
</DocumentElement>

Changes to System.Data.SQLite/SQLite3.cs.

168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
...
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
...
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
      n = UnsafeNativeMethods.sqlite3_reset_interop(stmt._sqlite_stmt);

      // If the schema changed, try and re-prepare it
      if (n == 17) // SQLITE_SCHEMA
      {
        // Recreate a dummy statement
        string str;
        using (SQLiteStatement tmp = Prepare(null, stmt._sqlStatement, null, out str))
        {
          // Finalize the existing statement
          stmt._sqlite_stmt.Dispose();
          // Reassign a new statement pointer to the old statement and clear the temporary one
          stmt._sqlite_stmt = tmp._sqlite_stmt;
          tmp._sqlite_stmt = null;

................................................................................
    }

    internal override string SQLiteLastError()
    {
      return SQLiteBase.SQLiteLastError(_sql);
    }

    internal override SQLiteStatement Prepare(SQLiteConnection cnn, string strSql, SQLiteStatement previous, out string strRemain)
    {
      IntPtr stmt = IntPtr.Zero;
      IntPtr ptr = IntPtr.Zero;
      int len = 0;
      int n = 17;
      int retries = 0;
      byte[] b = ToUTF8(strSql);
      string typedefs = null;
      SQLiteStatement cmd = null;



      GCHandle handle = GCHandle.Alloc(b, GCHandleType.Pinned);
      IntPtr psql = handle.AddrOfPinnedObject();

      try
      {
        while (n == 17 && retries < 3)
        {
          n = UnsafeNativeMethods.sqlite3_prepare_interop(_sql, psql, b.Length - 1, out stmt, out ptr, out len);
          retries++;

          if (n == 1)


          {
            if (String.Compare(SQLiteLastError(), "near \"TYPES\": syntax error", StringComparison.OrdinalIgnoreCase) == 0)
            {
              int pos = strSql.IndexOf(';');
              if (pos == -1) pos = strSql.Length - 1;

              typedefs = strSql.Substring(0, pos + 1);
              strSql = strSql.Substring(pos + 1);

              strRemain = "";

              while (cmd == null && strSql.Length > 0)
              {
                cmd = Prepare(cnn, strSql, previous, out strRemain);
                strSql = strRemain;
              }

              if (cmd != null)
                cmd.SetTypes(typedefs);

              return cmd;
................................................................................
                ISQLiteSchemaExtensions ext = ((IServiceProvider)SQLiteFactory.Instance).GetService(typeof(ISQLiteSchemaExtensions)) as ISQLiteSchemaExtensions;

                if (ext != null)
                  ext.BuildTempSchema(cnn);

                while (cmd == null && strSql.Length > 0)
                {
                  cmd = Prepare(cnn, strSql, previous, out strRemain);
                  strSql = strRemain;
                }

                return cmd;
              }
              finally
              {
                _buildingSchema = false;
              }
            }
#endif

















          }
        }

        if (n > 0) throw new SQLiteException(n, SQLiteLastError());

        strRemain = UTF8ToString(ptr, len);








|







 







|









>
>
>


<


|


<

|
>
>













|







 







|











>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
...
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
...
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
      n = UnsafeNativeMethods.sqlite3_reset_interop(stmt._sqlite_stmt);

      // If the schema changed, try and re-prepare it
      if (n == 17) // SQLITE_SCHEMA
      {
        // Recreate a dummy statement
        string str;
        using (SQLiteStatement tmp = Prepare(null, stmt._sqlStatement, null, (uint)(stmt._command._commandTimeout * 1000), out str))
        {
          // Finalize the existing statement
          stmt._sqlite_stmt.Dispose();
          // Reassign a new statement pointer to the old statement and clear the temporary one
          stmt._sqlite_stmt = tmp._sqlite_stmt;
          tmp._sqlite_stmt = null;

................................................................................
    }

    internal override string SQLiteLastError()
    {
      return SQLiteBase.SQLiteLastError(_sql);
    }

    internal override SQLiteStatement Prepare(SQLiteConnection cnn, string strSql, SQLiteStatement previous, uint timeoutMS, out string strRemain)
    {
      IntPtr stmt = IntPtr.Zero;
      IntPtr ptr = IntPtr.Zero;
      int len = 0;
      int n = 17;
      int retries = 0;
      byte[] b = ToUTF8(strSql);
      string typedefs = null;
      SQLiteStatement cmd = null;
      Random rnd = null;
      uint starttick = (uint)Environment.TickCount;

      GCHandle handle = GCHandle.Alloc(b, GCHandleType.Pinned);
      IntPtr psql = handle.AddrOfPinnedObject();

      try
      {
        while ((n == 17 || n == 6) && retries < 3)
        {
          n = UnsafeNativeMethods.sqlite3_prepare_interop(_sql, psql, b.Length - 1, out stmt, out ptr, out len);


          if (n == 17)
            retries++;
          else if (n == 1)
          {
            if (String.Compare(SQLiteLastError(), "near \"TYPES\": syntax error", StringComparison.OrdinalIgnoreCase) == 0)
            {
              int pos = strSql.IndexOf(';');
              if (pos == -1) pos = strSql.Length - 1;

              typedefs = strSql.Substring(0, pos + 1);
              strSql = strSql.Substring(pos + 1);

              strRemain = "";

              while (cmd == null && strSql.Length > 0)
              {
                cmd = Prepare(cnn, strSql, previous, timeoutMS, out strRemain);
                strSql = strRemain;
              }

              if (cmd != null)
                cmd.SetTypes(typedefs);

              return cmd;
................................................................................
                ISQLiteSchemaExtensions ext = ((IServiceProvider)SQLiteFactory.Instance).GetService(typeof(ISQLiteSchemaExtensions)) as ISQLiteSchemaExtensions;

                if (ext != null)
                  ext.BuildTempSchema(cnn);

                while (cmd == null && strSql.Length > 0)
                {
                  cmd = Prepare(cnn, strSql, previous, timeoutMS, out strRemain);
                  strSql = strRemain;
                }

                return cmd;
              }
              finally
              {
                _buildingSchema = false;
              }
            }
#endif
          }
          else if (n == 6) // Locked -- delay a small amount before retrying
          {
            // Keep trying
            if (rnd == null) // First time we've encountered the lock
              rnd = new Random();

            // If we've exceeded the command's timeout, give up and throw an error
            if ((uint)Environment.TickCount - starttick > timeoutMS)
            {
              throw new SQLiteException(n, SQLiteLastError());
            }
            else
            {
              // Otherwise sleep for a random amount of time up to 250ms
              UnsafeNativeMethods.sqlite3_sleep_interop((uint)rnd.Next(1, 250));
            }
          }
        }

        if (n > 0) throw new SQLiteException(n, SQLiteLastError());

        strRemain = UTF8ToString(ptr, len);

Changes to System.Data.SQLite/SQLiteBase.cs.

60
61
62
63
64
65
66

67
68
69
70
71
72
73
74
75
76
77
78

    /// <summary>
    /// Prepares a SQL statement for execution.
    /// </summary>
    /// <param name="cnn">The source connection preparing the command.  Can be null for any caller except LINQ</param>
    /// <param name="strSql">The SQL command text to prepare</param>
    /// <param name="previous">The previous statement in a multi-statement command, or null if no previous statement exists</param>

    /// <param name="strRemain">The remainder of the statement that was not processed.  Each call to prepare parses the
    /// SQL up to to either the end of the text or to the first semi-colon delimiter.  The remaining text is returned
    /// here for a subsequent call to Prepare() until all the text has been processed.</param>
    /// <returns>Returns an initialized SQLiteStatement.</returns>
    internal abstract SQLiteStatement Prepare(SQLiteConnection cnn, string strSql, SQLiteStatement previous, out string strRemain);
    /// <summary>
    /// Steps through a prepared statement.
    /// </summary>
    /// <param name="stmt">The SQLiteStatement to step through</param>
    /// <returns>True if a row was returned, False if not.</returns>
    internal abstract bool Step(SQLiteStatement stmt);
    /// <summary>







>




|







60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79

    /// <summary>
    /// Prepares a SQL statement for execution.
    /// </summary>
    /// <param name="cnn">The source connection preparing the command.  Can be null for any caller except LINQ</param>
    /// <param name="strSql">The SQL command text to prepare</param>
    /// <param name="previous">The previous statement in a multi-statement command, or null if no previous statement exists</param>
    /// <param name="timeoutMS">The timeout to wait before aborting the prepare</param>
    /// <param name="strRemain">The remainder of the statement that was not processed.  Each call to prepare parses the
    /// SQL up to to either the end of the text or to the first semi-colon delimiter.  The remaining text is returned
    /// here for a subsequent call to Prepare() until all the text has been processed.</param>
    /// <returns>Returns an initialized SQLiteStatement.</returns>
    internal abstract SQLiteStatement Prepare(SQLiteConnection cnn, string strSql, SQLiteStatement previous, uint timeoutMS, out string strRemain);
    /// <summary>
    /// Steps through a prepared statement.
    /// </summary>
    /// <param name="stmt">The SQLiteStatement to step through</param>
    /// <returns>True if a row was returned, False if not.</returns>
    internal abstract bool Step(SQLiteStatement stmt);
    /// <summary>

Changes to System.Data.SQLite/SQLiteCommand.cs.

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
...
460
461
462
463
464
465
466
467
468




469
470
471
472
473
474
475
      SQLiteStatement stmt = null;

      try
      {
        if (_statementList == null)
          _remainingText = _commandText;

        stmt = _cnn._sql.Prepare(_cnn, _remainingText, (_statementList == null) ? null : _statementList[_statementList.Count - 1], out _remainingText);
        if (stmt != null)
        {
          stmt._command = this;
          if (_statementList == null)
            _statementList = new List<SQLiteStatement>();

          _statementList.Add(stmt);
................................................................................
          if (value != null)
          {
            if (value._cnn != _cnn)
              throw new ArgumentException("Transaction is not associated with the command's connection");
          }
          _transaction = value;
        }
        else if (value != null)
          throw new ArgumentOutOfRangeException("SQLiteTransaction", "Not associated with a connection");




      }
    }

    /// <summary>
    /// Forwards to the local Transaction property
    /// </summary>
    protected override DbTransaction DbTransaction







|







 







|
<
>
>
>
>







223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
...
460
461
462
463
464
465
466
467

468
469
470
471
472
473
474
475
476
477
478
      SQLiteStatement stmt = null;

      try
      {
        if (_statementList == null)
          _remainingText = _commandText;

        stmt = _cnn._sql.Prepare(_cnn, _remainingText, (_statementList == null) ? null : _statementList[_statementList.Count - 1], (uint)(_commandTimeout * 1000), out _remainingText);
        if (stmt != null)
        {
          stmt._command = this;
          if (_statementList == null)
            _statementList = new List<SQLiteStatement>();

          _statementList.Add(stmt);
................................................................................
          if (value != null)
          {
            if (value._cnn != _cnn)
              throw new ArgumentException("Transaction is not associated with the command's connection");
          }
          _transaction = value;
        }
        else

        {
          Connection = value.Connection;
          _transaction = value;
        }
      }
    }

    /// <summary>
    /// Forwards to the local Transaction property
    /// </summary>
    protected override DbTransaction DbTransaction

Changes to System.Data.SQLite/SQLiteConnection.cs.

1009
1010
1011
1012
1013
1014
1015


1016
1017
1018
1019
1020
1021
1022
....
1410
1411
1412
1413
1414
1415
1416














































1417
1418
1419
1420
1421
1422
1423
....
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
        case "DATATYPES":
          return Schema_DataTypes();
        case "COLUMNS":
        case "TABLECOLUMNS":
          return Schema_Columns(parms[0], parms[2], parms[3]);
        case "INDEXES":
          return Schema_Indexes(parms[0], parms[2], parms[3]);


        case "INDEXCOLUMNS":
          return Schema_IndexColumns(parms[0], parms[2], parms[3], parms[4]);
        case "TABLES":
          return Schema_Tables(parms[0], parms[2], parms[3]);
        case "VIEWS":
          return Schema_Views(parms[0], parms[2]);
        case "VIEWCOLUMNS":
................................................................................
            catch (SQLiteException)
            {
            }
          }
        }
      }















































      tbl.AcceptChanges();
      tbl.EndLoadData();

      return tbl;
    }

    /// <summary>
................................................................................
                    row = tbl.NewRow();

                    row["VIEW_CATALOG"] = strCatalog;
                    row["VIEW_NAME"] = rdViews.GetString(2);
                    row["TABLE_CATALOG"] = strCatalog;
                    row["TABLE_SCHEMA"] = schemaRow[SchemaTableColumn.BaseSchemaName];
                    row["TABLE_NAME"] = schemaRow[SchemaTableColumn.BaseTableName];
                    row["COLUMN_NAME"] = schemaRow[SchemaTableColumn.ColumnName];
                    row["VIEW_COLUMN_NAME"] = viewRow[SchemaTableColumn.ColumnName];
                    row["COLUMN_HASDEFAULT"] = (viewRow[SchemaTableOptionalColumn.DefaultValue] != DBNull.Value);
                    row["COLUMN_DEFAULT"] = viewRow[SchemaTableOptionalColumn.DefaultValue];
                    row["ORDINAL_POSITION"] = viewRow[SchemaTableColumn.ColumnOrdinal];
                    row["IS_NULLABLE"] = viewRow[SchemaTableColumn.AllowDBNull];
                    row["DATA_TYPE"] = viewRow["DataTypeName"]; // SQLiteConvert.DbTypeToType((DbType)viewRow[SchemaTableColumn.ProviderType]).ToString();
                    row["EDM_TYPE"] = SQLiteConvert.DbTypeToTypeName((DbType)viewRow[SchemaTableColumn.ProviderType]).ToString();







>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|







1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
....
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
....
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
        case "DATATYPES":
          return Schema_DataTypes();
        case "COLUMNS":
        case "TABLECOLUMNS":
          return Schema_Columns(parms[0], parms[2], parms[3]);
        case "INDEXES":
          return Schema_Indexes(parms[0], parms[2], parms[3]);
        case "TRIGGERS":
          return Schema_Triggers(parms[0], parms[2], parms[3]);
        case "INDEXCOLUMNS":
          return Schema_IndexColumns(parms[0], parms[2], parms[3], parms[4]);
        case "TABLES":
          return Schema_Tables(parms[0], parms[2], parms[3]);
        case "VIEWS":
          return Schema_Views(parms[0], parms[2]);
        case "VIEWCOLUMNS":
................................................................................
            catch (SQLiteException)
            {
            }
          }
        }
      }

      tbl.AcceptChanges();
      tbl.EndLoadData();

      return tbl;
    }

    private DataTable Schema_Triggers(string catalog, string table, string triggerName)
    {
      DataTable tbl = new DataTable("Triggers");
      DataRow row;

      tbl.Locale = CultureInfo.InvariantCulture;
      tbl.Columns.Add("TABLE_CATALOG", typeof(string));
      tbl.Columns.Add("TABLE_SCHEMA", typeof(string));
      tbl.Columns.Add("TABLE_NAME", typeof(string));
      tbl.Columns.Add("TRIGGER_NAME", typeof(string));
      tbl.Columns.Add("TRIGGER_DEFINITION", typeof(string));

      tbl.BeginLoadData();

      if (String.IsNullOrEmpty(table)) table = null;
      if (String.IsNullOrEmpty(catalog)) catalog = "main";
      string master = (String.Compare(catalog, "temp", true, CultureInfo.InvariantCulture) == 0) ? _tempmasterdb : _masterdb;

      using (SQLiteCommand cmd = new SQLiteCommand(String.Format(CultureInfo.InvariantCulture, "SELECT [type], [name], [tbl_name], [rootpage], [sql], [rowid] FROM [{0}].[{1}] WHERE [type] LIKE 'trigger'", catalog, master), this))
      using (SQLiteDataReader rd = (SQLiteDataReader)cmd.ExecuteReader())
      {
        while (rd.Read())
        {
          if (String.Compare(rd.GetString(1), triggerName, true, CultureInfo.InvariantCulture) == 0
            || triggerName == null)
          {
            if (table == null || String.Compare(table, rd.GetString(2), true, CultureInfo.InvariantCulture) == 0)
            {
              row = tbl.NewRow();

              row["TABLE_CATALOG"] = catalog;
              row["TABLE_NAME"] = rd.GetString(2);
              row["TRIGGER_NAME"] = rd.GetString(1);
              row["TRIGGER_DEFINITION"] = rd.GetString(4);

              tbl.Rows.Add(row);
            }
          }
        }
      }
      tbl.AcceptChanges();
      tbl.EndLoadData();

      return tbl;
    }

    /// <summary>
................................................................................
                    row = tbl.NewRow();

                    row["VIEW_CATALOG"] = strCatalog;
                    row["VIEW_NAME"] = rdViews.GetString(2);
                    row["TABLE_CATALOG"] = strCatalog;
                    row["TABLE_SCHEMA"] = schemaRow[SchemaTableColumn.BaseSchemaName];
                    row["TABLE_NAME"] = schemaRow[SchemaTableColumn.BaseTableName];
                    row["COLUMN_NAME"] = schemaRow[SchemaTableColumn.BaseColumnName];
                    row["VIEW_COLUMN_NAME"] = viewRow[SchemaTableColumn.ColumnName];
                    row["COLUMN_HASDEFAULT"] = (viewRow[SchemaTableOptionalColumn.DefaultValue] != DBNull.Value);
                    row["COLUMN_DEFAULT"] = viewRow[SchemaTableOptionalColumn.DefaultValue];
                    row["ORDINAL_POSITION"] = viewRow[SchemaTableColumn.ColumnOrdinal];
                    row["IS_NULLABLE"] = viewRow[SchemaTableColumn.AllowDBNull];
                    row["DATA_TYPE"] = viewRow["DataTypeName"]; // SQLiteConvert.DbTypeToType((DbType)viewRow[SchemaTableColumn.ProviderType]).ToString();
                    row["EDM_TYPE"] = SQLiteConvert.DbTypeToTypeName((DbType)viewRow[SchemaTableColumn.ProviderType]).ToString();

Changes to bin/CompactFramework/System.Data.SQLite.DLL.

cannot compute difference between binary files

Changes to bin/CompactFramework/System.Data.SQLite.lib.

cannot compute difference between binary files

Changes to bin/CompactFramework/testce.exe.

cannot compute difference between binary files

Changes to bin/Designer/SQLite.Designer.dll.

cannot compute difference between binary files

Changes to bin/Designer/System.Data.SQLite.Linq.dll.

cannot compute difference between binary files

Changes to bin/Designer/System.Data.SQLite.Linq.pdb.

cannot compute difference between binary files

Changes to bin/Designer/install.exe.

cannot compute difference between binary files

Changes to bin/System.Data.SQLite.dll.

cannot compute difference between binary files

Changes to bin/System.Data.SQLite.lib.

cannot compute difference between binary files

Changes to bin/itanium/System.Data.SQLite.DLL.

cannot compute difference between binary files

Changes to bin/itanium/System.Data.SQLite.lib.

cannot compute difference between binary files

Changes to bin/test.exe.

cannot compute difference between binary files

Changes to bin/x64/System.Data.SQLite.DLL.

cannot compute difference between binary files

Changes to bin/x64/System.Data.SQLite.lib.

cannot compute difference between binary files

Changes to readme.htm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
..
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
...
116
117
118
119
120
121
122

















123
124
125
126
127
128
129
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
  </head>
  <body>
    ADO.NET 2.0 SQLite Data Provider<br>
    Version 1.0.52.0 July 16, 2008<br>
    Using SQLite 3.6.0<br>
    Written by Robert Simpson (<a href="mailto:robert@blackcastlesoft.com">robert@blackcastlesoft.com</a>)<br>
    Released to the public domain, use at your own risk!<br>
    Official provider website:&nbsp; <a href="http://sqlite.phxsoftware.com">http://sqlite.phxsoftware.com</a><br />
    <br>
    The latest version can be downloaded <a href="http://sourceforge.net/projects/sqlite-dotnet2">
      here</a>
................................................................................
      <LI>
      Written from scratch on VS2008 specifically for ADO.NET 2.0, implementing all the
      base classes and features recently introduced in the framework, including automatic
      transaction enlistment.<li>Supports the Full
        and Compact .NET Framework, as well as native C/C++ development.&nbsp; 100% binary
        compatible with the original sqlite3.dll.</li>
      <LI>
      On the Compact Framework, it is faster than the newly-introduced Sql Server 
      Mobile.  SQLite's installed size is a fraction of Sql Mobile's. It uses less memory at runtime, runs queries faster, and has a smaller database file size as well.
      <li>Encrypted database support.&nbsp; Encrypted databases are fully encrypted and
        support both binary and cleartext password types.</li>
      <LI>
      Visual Studio 2005/2008 Design-Time Support, works with all versions of VS2005/2008,
        including
      all Express Editions of VS2005.&nbsp; You can add a SQLite 
      database to the Servers list, design queries with the Query Designer, 
      drag-and-drop tables onto a Typed DataSet, etc.
      <LI>

      Single file redistributable.&nbsp; The core sqlite3 codebase and the ADO.NET wrapper 
      are combined into one multi-module assembly.
      <LI>
      Binaries included for Itanium, x64, x86 and ARM processors.
      <LI>
      DbProviderFactory support.
      <LI>
        Full support for ATTACH'ed databases.&nbsp; Exposed as <I>Catalogs</I>
      in the schema.&nbsp; When cloning a connection, all attached databases are 
      automatically re-attached to the new connection.
      <LI>
        DbConnection.GetSchema(...) support includes <I>ReservedWords, MetaDataCollections</I>, <I>DataSourceInformation</I>,
        <I>DataTypes, Columns</I>, <I>Tables</I>, <I>Views, ViewColumns, </I><I>Catalogs, </I><I>Indexes, 
          IndexColumns </I>and <EM>ForeignKeys</EM>
      .
      <LI>
      Enhanced DbDataReader.GetSchemaTable() functionality returns catalog, namespace 
      and detailed schema information even for complex queries.
      <LI>
      Named and unnamed parameters.
      <LI>
      Full UTF-8 and UTF-16 support, each with optimized pipelines into the native 
................................................................................
    <p>
      The core sqlite engine is compiled directly from the unmodified source code available
      at the sqlite.org website.&nbsp; Several additional pieces are compiled on top of
      it to extend its functionality, but the core engine's source is not changed.</p>
    <p></p>
    <p>
      <b>Version History</b></p>

















    <p><b>1.0.52.0 - July 16, 2008</b></p>
    <ul>
      <li>Code merge with SQLite 3.6.0</li>
      <li>Added a lot of previously-missing exports to the DEF file for the 
        native library.</li>
      <li>Fixed SQLiteDataReader to check for an invalid connection before operating on 
        an open cursor.</li>







|







 







|








|
|
>













|
<







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
..
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
...
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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
  </head>
  <body>
    ADO.NET 2.0 SQLite Data Provider<br>
    Version 1.0.53.0 July 24, 2008<br>
    Using SQLite 3.6.0<br>
    Written by Robert Simpson (<a href="mailto:robert@blackcastlesoft.com">robert@blackcastlesoft.com</a>)<br>
    Released to the public domain, use at your own risk!<br>
    Official provider website:&nbsp; <a href="http://sqlite.phxsoftware.com">http://sqlite.phxsoftware.com</a><br />
    <br>
    The latest version can be downloaded <a href="http://sourceforge.net/projects/sqlite-dotnet2">
      here</a>
................................................................................
      <LI>
      Written from scratch on VS2008 specifically for ADO.NET 2.0, implementing all the
      base classes and features recently introduced in the framework, including automatic
      transaction enlistment.<li>Supports the Full
        and Compact .NET Framework, as well as native C/C++ development.&nbsp; 100% binary
        compatible with the original sqlite3.dll.</li>
      <LI>
      On the Compact Framework, it is faster than Sql Server 
      Mobile.  SQLite's installed size is a fraction of Sql Mobile's. It uses less memory at runtime, runs queries faster, and has a smaller database file size as well.
      <li>Encrypted database support.&nbsp; Encrypted databases are fully encrypted and
        support both binary and cleartext password types.</li>
      <LI>
      Visual Studio 2005/2008 Design-Time Support, works with all versions of VS2005/2008,
        including
      all Express Editions of VS2005.&nbsp; You can add a SQLite 
      database to the Servers list, design queries with the Query Designer, 
      drag-and-drop tables onto a Typed DataSet, etc.<LI>
        Full SQLite schema editing inside Visual Studio.&nbsp;
        You can create/edit tables, views, triggers, indexes, check constraints and foreign keys.<LI>
      Single file redistributable.&nbsp; The core sqlite3 codebase and the ADO.NET wrapper 
      are combined into one multi-module assembly.
      <LI>
      Binaries included for Itanium, x64, x86 and ARM processors.
      <LI>
      DbProviderFactory support.
      <LI>
        Full support for ATTACH'ed databases.&nbsp; Exposed as <I>Catalogs</I>
      in the schema.&nbsp; When cloning a connection, all attached databases are 
      automatically re-attached to the new connection.
      <LI>
        DbConnection.GetSchema(...) support includes <I>ReservedWords, MetaDataCollections</I>, <I>DataSourceInformation</I>,
        <I>DataTypes, Columns</I>, <I>Tables</I>, <I>Views, ViewColumns, </I><I>Catalogs, </I><I>Indexes, 
          IndexColumns, </I><EM>ForeignKeys </EM>and<EM> Triggers</EM>.

      <LI>
      Enhanced DbDataReader.GetSchemaTable() functionality returns catalog, namespace 
      and detailed schema information even for complex queries.
      <LI>
      Named and unnamed parameters.
      <LI>
      Full UTF-8 and UTF-16 support, each with optimized pipelines into the native 
................................................................................
    <p>
      The core sqlite engine is compiled directly from the unmodified source code available
      at the sqlite.org website.&nbsp; Several additional pieces are compiled on top of
      it to extend its functionality, but the core engine's source is not changed.</p>
    <p></p>
    <p>
      <b>Version History</b></p>
    <p><b>1.0.53.0 - July 24, 2008</b></p>
    <ul>
      <li>Enabled sqlite_load_extension</li>
      <li>Added retry/timeout code to SQLite3.Prepare() when preparing statements for 
        execution and a SQLITE_BUSY error occurs.</li>
      <li>Added a new schema to SQLiteConnection.GetSchema() called <i>Triggers</i>.&nbsp; 
        Used to retrieve the trigger(s) associated with a database and/or table/view.</li>
      <li>Extensive updates to table/view editing capabilities inside Visual Studio&#39;s 
        Server Explorer.&nbsp; The program now parses and lets you edit CHECK constraints and 
        triggers on a table, as well as define triggers on views.&nbsp; Experimental 
        still, so e-mail me if you have issues.</li>
      <li>Minor bugfix to the ViewColumns schema to return the proper base column name 
        for a view that aliases a column.</li>
      <li>Fixed the insert/update/delete DML support in the Linq module.</li>
      <li>Changed the behavior of SQLiteCommand to allow a transaction to be set even if 
        the command hasn&#39;t been associated with a connection yet.</li>
    </ul>
    <p><b>1.0.52.0 - July 16, 2008</b></p>
    <ul>
      <li>Code merge with SQLite 3.6.0</li>
      <li>Added a lot of previously-missing exports to the DEF file for the 
        native library.</li>
      <li>Fixed SQLiteDataReader to check for an invalid connection before operating on 
        an open cursor.</li>

Changes to testlinq/Program.cs.

31
32
33
34
35
36
37
















38
39
40
41
42
43
44
                      select order;

          foreach (Orders o in query)
          {
            Console.WriteLine(o.OrderDate.ToString());
          }
        }

















        // This query fails due to a SQLite core issue.  Currently pending review by Dr. Hipp
        //{
        //  var query = from p in db.Products
        //              where p.Order_Details.Count(od => od.Orders.Customers.Country == p.Suppliers.Country) > 2
        //              select p;








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
                      select order;

          foreach (Orders o in query)
          {
            Console.WriteLine(o.OrderDate.ToString());
          }
        }

        {
          Categories c = new Categories();
          c.CategoryName = "Test Category";
          c.Description = "My Description";
          db.AddToCategories(c);
          db.SaveChanges();

          Console.WriteLine(c.CategoryID);

          c.Description = "My modified description";
          db.SaveChanges();

          db.DeleteObject(c);
          db.SaveChanges();
        }

        // This query fails due to a SQLite core issue.  Currently pending review by Dr. Hipp
        //{
        //  var query = from p in db.Products
        //              where p.Order_Details.Count(od => od.Orders.Customers.Country == p.Suppliers.Country) > 2
        //              select p;

Changes to testlinq/testlinq.csproj.

17
18
19
20
21
22
23

24
25
26
27
28
29
30
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>

  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>







>







17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>

Changes to testlinq/testlinq.csproj.user.

1
2
3
4




5
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
  </PropertyGroup>




</Project>




>
>
>
>

1
2
3
4
5
6
7
8
9
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <StartWorkingDirectory>
    </StartWorkingDirectory>
  </PropertyGroup>
</Project>

Changes to tools/install/InstallDesigner.cs.

657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
            subkey.SetValue("ProductName", "SQLite Data Provider");
            subkey.SetValue("ProductVersion", "1.0");
          }
        }

        using (RegistryKey key = Registry.LocalMachine.OpenSubKey(String.Format("Software\\Microsoft\\{0}\\{1}\\Menus", keyname, version), true))
        {
          key.SetValue("{DCBE6C8D-0E57-4099-A183-98FF74C64D9C}", ", 1000, 1");
        }

        using (RegistryKey key = Registry.LocalMachine.OpenSubKey(String.Format("Software\\Microsoft\\{0}\\{1}\\Services", keyname, version), true))
        {
          using (RegistryKey subkey = key.CreateSubKey("{DCBE6C8D-0E57-4099-A183-98FF74C64D9D}", RegistryKeyPermissionCheck.ReadWriteSubTree))
          {
            subkey.SetValue(null, "{DCBE6C8D-0E57-4099-A183-98FF74C64D9C}");







|







657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
            subkey.SetValue("ProductName", "SQLite Data Provider");
            subkey.SetValue("ProductVersion", "1.0");
          }
        }

        using (RegistryKey key = Registry.LocalMachine.OpenSubKey(String.Format("Software\\Microsoft\\{0}\\{1}\\Menus", keyname, version), true))
        {
          key.SetValue("{DCBE6C8D-0E57-4099-A183-98FF74C64D9C}", ", 1000, 2");
        }

        using (RegistryKey key = Registry.LocalMachine.OpenSubKey(String.Format("Software\\Microsoft\\{0}\\{1}\\Services", keyname, version), true))
        {
          using (RegistryKey subkey = key.CreateSubKey("{DCBE6C8D-0E57-4099-A183-98FF74C64D9D}", RegistryKeyPermissionCheck.ReadWriteSubTree))
          {
            subkey.SetValue(null, "{DCBE6C8D-0E57-4099-A183-98FF74C64D9C}");

Changes to tools/install/Resources/System.Data.SQLite.dll.

cannot compute difference between binary files

Changes to tools/setup/exe/setup/setup.rc.

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
..
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

/////////////////////////////////////////////////////////////////////////////
//
// Version
//

VS_VERSION_INFO VERSIONINFO
 FILEVERSION 1,0,52,0
 PRODUCTVERSION 1,0,0,0
 FILEFLAGSMASK 0x17L
#ifdef _DEBUG
 FILEFLAGS 0x1L
#else
 FILEFLAGS 0x0L
#endif
................................................................................
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904b0"
        BEGIN
            VALUE "Comments", "http://sqlite.phxsoftware.com"
            VALUE "FileDescription", "SQLite ADO.NET 2.0 Setup"
            VALUE "FileVersion", "1.0.52.0"
            VALUE "InternalName", "setup"
            VALUE "LegalCopyright", "Released to the public domain"
            VALUE "OriginalFilename", "setup.exe"
            VALUE "ProductName", "System.Data.SQLite"
            VALUE "ProductVersion", "1.0"
        END
    END







|







 







|







53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
..
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

/////////////////////////////////////////////////////////////////////////////
//
// Version
//

VS_VERSION_INFO VERSIONINFO
 FILEVERSION 1,0,53,0
 PRODUCTVERSION 1,0,0,0
 FILEFLAGSMASK 0x17L
#ifdef _DEBUG
 FILEFLAGS 0x1L
#else
 FILEFLAGS 0x0L
#endif
................................................................................
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904b0"
        BEGIN
            VALUE "Comments", "http://sqlite.phxsoftware.com"
            VALUE "FileDescription", "SQLite ADO.NET 2.0 Setup"
            VALUE "FileVersion", "1.0.53.0"
            VALUE "InternalName", "setup"
            VALUE "LegalCopyright", "Released to the public domain"
            VALUE "OriginalFilename", "setup.exe"
            VALUE "ProductName", "System.Data.SQLite"
            VALUE "ProductVersion", "1.0"
        END
    END

Changes to tools/setup/sqlite_setup.suo.

cannot compute difference between binary files

Changes to tools/setup/sqlite_setup.vdproj.

70
71
72
73
74
75
76












77
78
79
80
81
82
83
...
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
...
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
...
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
...
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
...
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
...
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
...
787
788
789
790
791
792
793































794
795
796
797
798
799
800
801
802
803
804
805
806
...
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
...
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
....
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
....
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
....
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
        "Entry"
        {
        "MsmKey" = "8:_3578C7AADEF926410602B18EDBBEFFF9"
        "OwnerKey" = "8:_244D4945EA335F5E4E54085BFD020CC1"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"












        {
        "MsmKey" = "8:_40DFF08BA903482D807E715A041CA8B1"
        "OwnerKey" = "8:_UNDEFINED"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
................................................................................
        {
        "MsmKey" = "8:_60E2C442F77C48DE8150EBFC86663225"
        "OwnerKey" = "8:_UNDEFINED"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_7E792650E0F6405E96F6348CA9F40A9C"
        "OwnerKey" = "8:_CD3CE5CDAB13405EA6EAAADC95F88D2E"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_8E01D0B6DA05822B53D22C15E25DB4A3"
        "OwnerKey" = "8:_7E792650E0F6405E96F6348CA9F40A9C"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_9352653B827F735B8C3BE81D11522ECC"
        "OwnerKey" = "8:_B00FB4712154B7A5894294702C96689D"
        "MsmSig" = "8:_UNDEFINED"
................................................................................
        }
        "Entry"
        {
        "MsmKey" = "8:_A1873A8DC29649A4BAF00E155CDCB8BF"
        "OwnerKey" = "8:_UNDEFINED"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_A18DBDB7776215EAD9A52C96F8CA1E91"
        "OwnerKey" = "8:_40F352185F3B41A485F42BFC64BF9162"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_A7448E608040319F6C5E12637881B1F6"
        "OwnerKey" = "8:_CD3CE5CDAB13405EA6EAAADC95F88D2E"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
................................................................................
        {
        "MsmKey" = "8:_E6DB5A9B08AC4645A19C948BBFDD0348"
        "OwnerKey" = "8:_244D4945EA335F5E4E54085BFD020CC1"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_F320FBAE871DA320178BEEA242900CC7"
        "OwnerKey" = "8:_2C7EDFF06B61482393D94E3A63D90113"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_B29C75F5F4D24817846DCEF9951068E1"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
................................................................................
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_CD3CE5CDAB13405EA6EAAADC95F88D2E"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_7E792650E0F6405E96F6348CA9F40A9C"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_B00FB4712154B7A5894294702C96689D"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
................................................................................
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_40F352185F3B41A485F42BFC64BF9162"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_A18DBDB7776215EAD9A52C96F8CA1E91"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_40DFF08BA903482D807E715A041CA8B1"
        "MsmSig" = "8:_UNDEFINED"
................................................................................
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_2C7EDFF06B61482393D94E3A63D90113"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_F320FBAE871DA320178BEEA242900CC7"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_29B62FDE3E56411381A6E8B358CBB0F5"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_244D4945EA335F5E4E54085BFD020CC1"
        "MsmSig" = "8:_UNDEFINED"
................................................................................
            "IsDependency" = "11:FALSE"
            "IsolateTo" = "8:"
            }
            "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_2C7EDFF06B61482393D94E3A63D90113"
            {
            "AssemblyRegister" = "3:1"
            "AssemblyIsInGAC" = "11:FALSE"
            "AssemblyAsmDisplayName" = "8:test, Version=1.0.0.29409, Culture=neutral, processorArchitecture=x86"
                "ScatterAssemblies"
                {
                    "_2C7EDFF06B61482393D94E3A63D90113"
                    {
                    "Name" = "8:test.exe"
                    "Attributes" = "3:512"
                    }
................................................................................
            "Permanent" = "11:FALSE"
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:TRUE"
            "IsDependency" = "11:TRUE"
            "IsolateTo" = "8:"































            }
            "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_40DFF08BA903482D807E715A041CA8B1"
            {
            "AssemblyRegister" = "3:1"
            "AssemblyIsInGAC" = "11:FALSE"
            "AssemblyAsmDisplayName" = "8:install, Version=1.0.0.28167, Culture=neutral, processorArchitecture=x86"
                "ScatterAssemblies"
                {
                    "_40DFF08BA903482D807E715A041CA8B1"
                    {
                    "Name" = "8:install.exe"
                    "Attributes" = "3:512"
                    }
................................................................................
            "IsDependency" = "11:FALSE"
            "IsolateTo" = "8:"
            }
            "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_40F352185F3B41A485F42BFC64BF9162"
            {
            "AssemblyRegister" = "3:1"
            "AssemblyIsInGAC" = "11:FALSE"
            "AssemblyAsmDisplayName" = "8:testce, Version=1.0.0.29384, Culture=neutral, processorArchitecture=MSIL"
                "ScatterAssemblies"
                {
                    "_40F352185F3B41A485F42BFC64BF9162"
                    {
                    "Name" = "8:testce.exe"
                    "Attributes" = "3:512"
                    }
................................................................................
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:FALSE"
            "IsDependency" = "11:FALSE"
            "IsolateTo" = "8:"
            }
            "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_7E792650E0F6405E96F6348CA9F40A9C"
            {
            "AssemblyRegister" = "3:1"
            "AssemblyIsInGAC" = "11:TRUE"
            "AssemblyAsmDisplayName" = "8:Microsoft.VisualStudio.CommandBars, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
                "ScatterAssemblies"
                {
                    "_7E792650E0F6405E96F6348CA9F40A9C"
                    {
                    "Name" = "8:Microsoft.VisualStudio.CommandBars.dll"
                    "Attributes" = "3:512"
                    }
                }
            "SourcePath" = "8:Microsoft.VisualStudio.CommandBars.dll"
            "TargetName" = "8:"
            "Tag" = "8:"
            "Folder" = "8:_F11D54EE0EEA4BF59B52E621630B6A2E"
            "Condition" = "8:"
            "Transitive" = "11:FALSE"
            "Vital" = "11:TRUE"
            "ReadOnly" = "11:FALSE"
            "Hidden" = "11:FALSE"
            "System" = "11:FALSE"
            "Permanent" = "11:FALSE"
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:TRUE"
            "IsDependency" = "11:TRUE"
            "IsolateTo" = "8:"
            }
            "{1FB2D0AE-D3B9-43D4-B9DD-F88EC61E35DE}:_8E01D0B6DA05822B53D22C15E25DB4A3"
            {
            "SourcePath" = "8:vsmso.olb"
            "TargetName" = "8:vsmso.olb"
            "Tag" = "8:"
            "Folder" = "8:_F11D54EE0EEA4BF59B52E621630B6A2E"
            "Condition" = "8:"
            "Transitive" = "11:FALSE"
            "Vital" = "11:TRUE"
            "ReadOnly" = "11:FALSE"
            "Hidden" = "11:FALSE"
            "System" = "11:FALSE"
            "Permanent" = "11:FALSE"
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:TRUE"
            "IsDependency" = "11:TRUE"
            "IsolateTo" = "8:"
            }
            "{1FB2D0AE-D3B9-43D4-B9DD-F88EC61E35DE}:_9352653B827F735B8C3BE81D11522ECC"
            {
            "SourcePath" = "8:dte80a.olb"
            "TargetName" = "8:dte80a.olb"
................................................................................
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:FALSE"
            "IsDependency" = "11:FALSE"
            "IsolateTo" = "8:"
            }
            "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_A18DBDB7776215EAD9A52C96F8CA1E91"
            {
            "AssemblyRegister" = "3:1"
            "AssemblyIsInGAC" = "11:FALSE"
            "AssemblyAsmDisplayName" = "8:System.Data.SQLite, Version=1.0.52.0, Culture=neutral, PublicKeyToken=1fdb50b1b62b4c84, processorArchitecture=x86"
                "ScatterAssemblies"
                {
                    "_A18DBDB7776215EAD9A52C96F8CA1E91"
                    {
                    "Name" = "8:System.Data.SQLite.DLL"
                    "Attributes" = "3:512"
                    }
                }
            "SourcePath" = "8:System.Data.SQLite.DLL"
            "TargetName" = "8:"
            "Tag" = "8:"
            "Folder" = "8:_10C8E86E2EEF451BB40F774C35C5466F"
            "Condition" = "8:"
            "Transitive" = "11:FALSE"
            "Vital" = "11:TRUE"
            "ReadOnly" = "11:FALSE"
            "Hidden" = "11:FALSE"
            "System" = "11:FALSE"
            "Permanent" = "11:FALSE"
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:FALSE"
            "IsDependency" = "11:TRUE"
            "IsolateTo" = "8:"
            }
            "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_A7448E608040319F6C5E12637881B1F6"
            {
            "AssemblyRegister" = "3:1"
            "AssemblyIsInGAC" = "11:TRUE"
            "AssemblyAsmDisplayName" = "8:Microsoft.VisualStudio.Shell, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
                "ScatterAssemblies"
                {
................................................................................
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:TRUE"
            "IsDependency" = "11:TRUE"
            "IsolateTo" = "8:"
            }
            "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_F320FBAE871DA320178BEEA242900CC7"
            {
            "AssemblyRegister" = "3:1"
            "AssemblyIsInGAC" = "11:FALSE"
            "AssemblyAsmDisplayName" = "8:System.Data.SQLite, Version=1.0.52.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86"
                "ScatterAssemblies"
                {
                    "_F320FBAE871DA320178BEEA242900CC7"
                    {
                    "Name" = "8:System.Data.SQLite.DLL"
                    "Attributes" = "3:512"
                    }
                }
            "SourcePath" = "8:System.Data.SQLite.DLL"
            "TargetName" = "8:"
            "Tag" = "8:"
            "Folder" = "8:_30C77BF2E6E84D01ADE5FB8BA2F81504"
            "Condition" = "8:"
            "Transitive" = "11:FALSE"
            "Vital" = "11:TRUE"
            "ReadOnly" = "11:FALSE"
            "Hidden" = "11:FALSE"
            "System" = "11:FALSE"
            "Permanent" = "11:FALSE"
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:FALSE"
            "IsDependency" = "11:TRUE"
            "IsolateTo" = "8:"
            }
        }
        "FileType"
        {
        }
        "Folder"
        {
            "{3C67513D-01DD-4637-8A68-80971EB9504F}:_A0841E79B7874F7288672343934C7657"
................................................................................
        "LangId" = "3:1033"
        "RequiresElevation" = "11:FALSE"
        }
        "Product"
        {
        "Name" = "8:Microsoft Visual Studio"
        "ProductName" = "8:SQLite ADO.NET 2.0 Provider"
        "ProductCode" = "8:{B49C3E5D-D0E6-4399-ABDB-FCFC2AEE50A9}"
        "PackageCode" = "8:{8FF57310-A0E7-4843-839A-2C0EB7B2E7D3}"
        "UpgradeCode" = "8:{78329A82-AFB1-453B-AF00-D46AC911DA89}"
        "RestartWWWService" = "11:FALSE"
        "RemovePreviousVersions" = "11:TRUE"
        "DetectNewerInstalledVersion" = "11:TRUE"
        "InstallAllUsers" = "11:TRUE"
        "ProductVersion" = "8:1.052.0"
        "Manufacturer" = "8:Phoenix Software Solutions, LLC"
        "ARPHELPTELEPHONE" = "8:"
        "ARPHELPLINK" = "8:http://sqlite.phxsoftware.com"
        "Title" = "8:SQLite ADO.NET 2.0 Provider"
        "Subject" = "8:"
        "ARPCONTACT" = "8:Phoenix Software Solutions, LLC"
        "Keywords" = "8:"







>
>
>
>
>
>
>
>
>
>
>
>







 







|
|
<
<
<
<
<
<







 







<
<
<
<
<
<







 







<
<
<
<
<
<







 







<
<
<
<
<
<







 







|







 







|





|







 







|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





|







 







|







 







|



|


|

|



|


|










|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







|
|





|







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
...
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
...
269
270
271
272
273
274
275






276
277
278
279
280
281
282
...
291
292
293
294
295
296
297






298
299
300
301
302
303
304
...
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
...
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
...
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
...
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
...
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
...
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
....
1022
1023
1024
1025
1026
1027
1028































1029
1030
1031
1032
1033
1034
1035
....
1308
1309
1310
1311
1312
1313
1314































1315
1316
1317
1318
1319
1320
1321
....
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
        "Entry"
        {
        "MsmKey" = "8:_3578C7AADEF926410602B18EDBBEFFF9"
        "OwnerKey" = "8:_244D4945EA335F5E4E54085BFD020CC1"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_3FC53DB84F275D50099C4F2A30AE6DC3"
        "OwnerKey" = "8:_29B62FDE3E56411381A6E8B358CBB0F5"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_3FC53DB84F275D50099C4F2A30AE6DC3"
        "OwnerKey" = "8:_2C7EDFF06B61482393D94E3A63D90113"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_40DFF08BA903482D807E715A041CA8B1"
        "OwnerKey" = "8:_UNDEFINED"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
................................................................................
        {
        "MsmKey" = "8:_60E2C442F77C48DE8150EBFC86663225"
        "OwnerKey" = "8:_UNDEFINED"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_7A5526750394E83A77FEAF65EFEF3719"
        "OwnerKey" = "8:_40F352185F3B41A485F42BFC64BF9162"






        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_9352653B827F735B8C3BE81D11522ECC"
        "OwnerKey" = "8:_B00FB4712154B7A5894294702C96689D"
        "MsmSig" = "8:_UNDEFINED"
................................................................................
        }
        "Entry"
        {
        "MsmKey" = "8:_A1873A8DC29649A4BAF00E155CDCB8BF"
        "OwnerKey" = "8:_UNDEFINED"
        "MsmSig" = "8:_UNDEFINED"
        }






        "Entry"
        {
        "MsmKey" = "8:_A7448E608040319F6C5E12637881B1F6"
        "OwnerKey" = "8:_CD3CE5CDAB13405EA6EAAADC95F88D2E"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
................................................................................
        {
        "MsmKey" = "8:_E6DB5A9B08AC4645A19C948BBFDD0348"
        "OwnerKey" = "8:_244D4945EA335F5E4E54085BFD020CC1"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {






        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_B29C75F5F4D24817846DCEF9951068E1"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
................................................................................
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_CD3CE5CDAB13405EA6EAAADC95F88D2E"
        "MsmSig" = "8:_UNDEFINED"
        }






        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_B00FB4712154B7A5894294702C96689D"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
................................................................................
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_40F352185F3B41A485F42BFC64BF9162"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_7A5526750394E83A77FEAF65EFEF3719"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_40DFF08BA903482D807E715A041CA8B1"
        "MsmSig" = "8:_UNDEFINED"
................................................................................
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_2C7EDFF06B61482393D94E3A63D90113"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_29B62FDE3E56411381A6E8B358CBB0F5"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_3FC53DB84F275D50099C4F2A30AE6DC3"
        "MsmSig" = "8:_UNDEFINED"
        }
        "Entry"
        {
        "MsmKey" = "8:_UNDEFINED"
        "OwnerKey" = "8:_244D4945EA335F5E4E54085BFD020CC1"
        "MsmSig" = "8:_UNDEFINED"
................................................................................
            "IsDependency" = "11:FALSE"
            "IsolateTo" = "8:"
            }
            "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_2C7EDFF06B61482393D94E3A63D90113"
            {
            "AssemblyRegister" = "3:1"
            "AssemblyIsInGAC" = "11:FALSE"
            "AssemblyAsmDisplayName" = "8:test, Version=1.0.0.41107, Culture=neutral, processorArchitecture=x86"
                "ScatterAssemblies"
                {
                    "_2C7EDFF06B61482393D94E3A63D90113"
                    {
                    "Name" = "8:test.exe"
                    "Attributes" = "3:512"
                    }
................................................................................
            "Permanent" = "11:FALSE"
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:TRUE"
            "IsDependency" = "11:TRUE"
            "IsolateTo" = "8:"
            }
            "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_3FC53DB84F275D50099C4F2A30AE6DC3"
            {
            "AssemblyRegister" = "3:1"
            "AssemblyIsInGAC" = "11:TRUE"
            "AssemblyAsmDisplayName" = "8:System.Data.SQLite, Version=1.0.53.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86"
                "ScatterAssemblies"
                {
                    "_3FC53DB84F275D50099C4F2A30AE6DC3"
                    {
                    "Name" = "8:System.Data.SQLite.dll"
                    "Attributes" = "3:512"
                    }
                }
            "SourcePath" = "8:System.Data.SQLite.dll"
            "TargetName" = "8:"
            "Tag" = "8:"
            "Folder" = "8:_F11D54EE0EEA4BF59B52E621630B6A2E"
            "Condition" = "8:"
            "Transitive" = "11:FALSE"
            "Vital" = "11:TRUE"
            "ReadOnly" = "11:FALSE"
            "Hidden" = "11:FALSE"
            "System" = "11:FALSE"
            "Permanent" = "11:FALSE"
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:FALSE"
            "IsDependency" = "11:TRUE"
            "IsolateTo" = "8:"
            }
            "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_40DFF08BA903482D807E715A041CA8B1"
            {
            "AssemblyRegister" = "3:1"
            "AssemblyIsInGAC" = "11:FALSE"
            "AssemblyAsmDisplayName" = "8:install, Version=1.0.0.41201, Culture=neutral, processorArchitecture=x86"
                "ScatterAssemblies"
                {
                    "_40DFF08BA903482D807E715A041CA8B1"
                    {
                    "Name" = "8:install.exe"
                    "Attributes" = "3:512"
                    }
................................................................................
            "IsDependency" = "11:FALSE"
            "IsolateTo" = "8:"
            }
            "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_40F352185F3B41A485F42BFC64BF9162"
            {
            "AssemblyRegister" = "3:1"
            "AssemblyIsInGAC" = "11:FALSE"
            "AssemblyAsmDisplayName" = "8:testce, Version=1.0.0.41030, Culture=neutral, processorArchitecture=MSIL"
                "ScatterAssemblies"
                {
                    "_40F352185F3B41A485F42BFC64BF9162"
                    {
                    "Name" = "8:testce.exe"
                    "Attributes" = "3:512"
                    }
................................................................................
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:FALSE"
            "IsDependency" = "11:FALSE"
            "IsolateTo" = "8:"
            }
            "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_7A5526750394E83A77FEAF65EFEF3719"
            {
            "AssemblyRegister" = "3:1"
            "AssemblyIsInGAC" = "11:TRUE"
            "AssemblyAsmDisplayName" = "8:System.Data.SQLite, Version=1.0.53.0, Culture=neutral, PublicKeyToken=1fdb50b1b62b4c84, processorArchitecture=MSIL"
                "ScatterAssemblies"
                {
                    "_7A5526750394E83A77FEAF65EFEF3719"
                    {
                    "Name" = "8:System.Data.SQLite.dll"
                    "Attributes" = "3:512"
                    }
                }
            "SourcePath" = "8:System.Data.SQLite.dll"
            "TargetName" = "8:"
            "Tag" = "8:"
            "Folder" = "8:_10C8E86E2EEF451BB40F774C35C5466F"
            "Condition" = "8:"
            "Transitive" = "11:FALSE"
            "Vital" = "11:TRUE"
            "ReadOnly" = "11:FALSE"
            "Hidden" = "11:FALSE"
            "System" = "11:FALSE"
            "Permanent" = "11:FALSE"
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:FALSE"




















            "IsDependency" = "11:TRUE"
            "IsolateTo" = "8:"
            }
            "{1FB2D0AE-D3B9-43D4-B9DD-F88EC61E35DE}:_9352653B827F735B8C3BE81D11522ECC"
            {
            "SourcePath" = "8:dte80a.olb"
            "TargetName" = "8:dte80a.olb"
................................................................................
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:FALSE"
            "IsDependency" = "11:FALSE"
            "IsolateTo" = "8:"
            }































            "{9F6F8455-1EF1-4B85-886A-4223BCC8E7F7}:_A7448E608040319F6C5E12637881B1F6"
            {
            "AssemblyRegister" = "3:1"
            "AssemblyIsInGAC" = "11:TRUE"
            "AssemblyAsmDisplayName" = "8:Microsoft.VisualStudio.Shell, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
                "ScatterAssemblies"
                {
................................................................................
            "SharedLegacy" = "11:FALSE"
            "PackageAs" = "3:1"
            "Register" = "3:1"
            "Exclude" = "11:TRUE"
            "IsDependency" = "11:TRUE"
            "IsolateTo" = "8:"
            }































        }
        "FileType"
        {
        }
        "Folder"
        {
            "{3C67513D-01DD-4637-8A68-80971EB9504F}:_A0841E79B7874F7288672343934C7657"
................................................................................
        "LangId" = "3:1033"
        "RequiresElevation" = "11:FALSE"
        }
        "Product"
        {
        "Name" = "8:Microsoft Visual Studio"
        "ProductName" = "8:SQLite ADO.NET 2.0 Provider"
        "ProductCode" = "8:{D8D32653-DDF3-4811-9BFE-95455003DCF2}"
        "PackageCode" = "8:{D8EEE4A0-04AA-41D9-B3DA-B42BA7E7CA60}"
        "UpgradeCode" = "8:{78329A82-AFB1-453B-AF00-D46AC911DA89}"
        "RestartWWWService" = "11:FALSE"
        "RemovePreviousVersions" = "11:TRUE"
        "DetectNewerInstalledVersion" = "11:TRUE"
        "InstallAllUsers" = "11:TRUE"
        "ProductVersion" = "8:1.053.0"
        "Manufacturer" = "8:Phoenix Software Solutions, LLC"
        "ARPHELPTELEPHONE" = "8:"
        "ARPHELPLINK" = "8:http://sqlite.phxsoftware.com"
        "Title" = "8:SQLite ADO.NET 2.0 Provider"
        "Subject" = "8:"
        "ARPCONTACT" = "8:Phoenix Software Solutions, LLC"
        "Keywords" = "8:"