<?xml version="1.0" encoding="utf-8"?>
<page xmlns="http://projectmallard.org/1.0/" xmlns:its="http://www.w3.org/2005/11/its" type="topic" id="record-collection.js" lang="sv">

  <info>
  <title type="text">Skivsamling (Javascript)</title>
    <link type="guide" xref="js#examples"/>

    <desc>Skapa ett litet databasprogram för att få ordning på din musiksamling</desc>

    <revision pkgversion="0.1" version="0.1" date="2011-02-22" status="review"/>
    <credit type="author">
      <name>Dokumentationsprojekt för GNOME</name>
      <email its:translate="no">gnome-doc-list@gnome.org</email>
    </credit>
    <credit type="author">
      <name>Johannes Schmid</name>
      <email its:translate="no">jhs@gnome.org</email>
    </credit>
    <credit type="editor">
      <name>Marta Maria Casetti</name>
      <email its:translate="no">mmcasettii@gmail.com</email>
      <years>2013</years>
    </credit>
  <credit type="translator copyright"><name>Sebastian Rasmussen</name><email>sebras@gmail.com</email><years>2019</years></credit><credit type="translator copyright"><name>Anders Jonsson</name><email>anders.jonsson@norsjovallen.se</email><years>2021</years></credit></info>

<title>Skivsamling</title>

<synopsis>
  <p>I denna handledning kommer du lära dig:</p>
  <list>
    <item><p>Hur du ansluter till en databas med libgda</p></item>
    <item><p>How to insert and browse records in a database table</p></item>
  </list>
</synopsis>

<section id="intro">
  <title>Introduktion</title>
  <p>Denna demonstration använder språket Javascript. Vi kommer att demonstrera hur du ansluter till och använder en databas från ett GTK-program, genom att använda biblioteket GDA (GNOME Data Access). Därmed behöver du även ha detta bibliotek installerat.</p>
  <p>
    GNOME Data Access (GDA) is library whose purpose is to provide universal access to different kinds and types of data sources. This goes from traditional relational database systems, to any imaginable kind of data source such as a mail server, a LDAP directory, etc. For more information, and for a full API and documentation, visit the <link href="http://library.gnome.org/devel/libgda/stable/">GDA website</link>.
  </p>
  <p>
    Although a big part of the code is related to user interface (GUI), we are going to focus our tutorial on the database parts (we might mention other parts we think are relevant though). To know more about Javascript programs in GNOME, see the <link xref="image-viewer.js">Image Viewer program</link> tutorial.
  </p>
</section>

<section id="anjuta">
  <title>Skapa ett projekt i Anjuta</title>
  <p>Innan du börjar koda kommer du behöva konfigurera ett nytt projekt i Anjuta. Detta kommer skapa alla filer som du behöver för att bygga och köra koden senare. Det är också användbart för att hålla allting samlat.</p>
  <steps>
    <item>
    <p>Starta Anjuta och klicka på <guiseq><gui>Arkiv</gui><gui>Ny</gui><gui>Projekt</gui></guiseq> för att öppna projektguiden.</p>
    </item>
    <item>
    <p>Välj <gui>Allmän Javascript</gui> från fliken <gui>JS</gui>, klicka på <gui>Framåt</gui>, och fyll i dina detaljer på de nästkommande sidorna. Använd <file>record-collection</file> som projektnamn och katalog.</p>
   	</item>
    <item>
    <p>Klicka på <gui>Färdig</gui> så kommer projektet skapas åt dig. Öppna <file>src/main.js</file> från flikarna <gui>Projekt</gui> eller <gui>Filer</gui>. Den innehåller väldigt enkel exempelkod.</p>
    </item>
  </steps>
</section>

<section id="structure">
  <title>Programstruktur</title>
  <media type="image" mime="image/png" src="media/record-collection.png"/>
  <p>This demo is a simple GTK application (with a single window) capable of inserting records into a database table as well as browsing all records of the table. The table has two fields: <code>id</code>, an integer, and <code>name</code>, a varchar. The first section (on the top) of the application allows you to insert a record into the table. The last section (bottom) allows you to see all the records of that table. Its content is refreshed every time a new record is inserted and on the application startup.
  </p>
</section>

<section id="start">
  <title>Starta det roliga</title>
  <p>Låt oss starta genom att undersöka programmets skelett:</p>
  <code mime="application/javascript" style="numbered">
const GLib = imports.gi.GLib;
const Gtk = imports.gi.Gtk;
const Gda = imports.gi.Gda;
const Lang = imports.lang;

function Demo () {
  this._init ();
}

Demo.prototype = {

  _init: function () {
    this.setupWindow ();
    this.setupDatabase ();
    this.selectData ();
  }
}

Gtk.init (null, null);

var demo = new Demo ();

Gtk.main ();</code>
  <list>
    <item><p>Rad 1‒4: Initiala importer. Var särskilt uppmärksam på rad 3, som säger till Javascript att importera GDA-biblioteket, vårt fokus i denna handledning.</p></item>
    <item><p>Rad 6‒17: Definiera vår klass <code>Demo</code>. Var särskilt uppmärksam på rad 13‒15, där vi anropar tre metoder som gör hela jobbet. De kommer beskrivas i detalj nedan.</p></item>
    <item><p>Rad 19‒23: Starta programmet.</p></item>
  </list>
</section>

<section id="design">
  <title>Designa programmet</title>
  <p>Låt oss ta en titt på metoden <code>setupWindow</code>. Den ansvarar för att skapa användargränssnittet (UI). Då UI inte är vårt fokus kommer vi endast förklara de relevanta delarna.</p>
  <code mime="application/javascript" style="numbered">
  setupWindow: function () {
    this.window = new Gtk.Window ({title: "Data Access Demo", height_request: 350});
    this.window.connect ("delete-event", function () {
      Gtk.main_quit();
      return true;
      });

    // main box
    var main_box = new Gtk.Box ({orientation: Gtk.Orientation.VERTICAL, spacing: 5});
    this.window.add (main_box);

    // first label
    var info1 = new Gtk.Label ({label: "&lt;b&gt;Insert a record&lt;/b&gt;", xalign: 0, use_markup: true});
    main_box.pack_start (info1, false, false, 5);

    // "insert a record" horizontal box
    var insert_box = new Gtk.Box ({orientation: Gtk.Orientation.HORIZONTAL, spacing: 5});
    main_box.pack_start (insert_box, false, false, 5);

    // ID field
    insert_box.pack_start (new Gtk.Label ({label: "ID:"}), false, false, 5);
    this.id_entry = new Gtk.Entry ();
    insert_box.pack_start (this.id_entry, false, false, 5);

    // Name field
    insert_box.pack_start (new Gtk.Label ({label: "Name:"}), false, false, 5);
    this.name_entry = new Gtk.Entry ({activates_default: true});
    insert_box.pack_start (this.name_entry, true, true, 5);

    // Insert button
    var insert_button = new Gtk.Button ({label: "Insert", can_default: true});
    insert_button.connect ("clicked", Lang.bind (this, this._insertClicked));
    insert_box.pack_start (insert_button, false, false, 5);
    insert_button.grab_default ();

    // Browse textview
    var info2 = new Gtk.Label ({label: "&lt;b&gt;Browse the table&lt;/b&gt;", xalign: 0, use_markup: true});
    main_box.pack_start (info2, false, false, 5);
    this.text = new Gtk.TextView ({editable: false});
    var sw = new Gtk.ScrolledWindow ({shadow_type:Gtk.ShadowType.IN});
    sw.add (this.text);
    main_box.pack_start (sw, true, true, 5);

    this.count_label = new Gtk.Label ({label: "", xalign: 0, use_markup: true});
    main_box.pack_start (this.count_label, false, false, 0);

    this.window.show_all ();
  },</code>
  <list>
    <item><p>Lines 22 and 27: Create the 2 entries (for the two fields) in which users will type something to get inserted in the database.</p></item>
    <item><p>Lines 31‒34: Create the Insert button. We connect its <code>clicked</code> signal to the <code>_insertClicked</code> private method of the class. This method is detailed below.</p></item>
    <item><p>Rad 39: Skapa komponenten (<code>TextView</code>) där vi kommer visa tabellens innehåll.</p></item>
    <item><p>Line 44: Create the label where we will show the number of records in the table. Initially it's empty, it will be updated later.</p></item>
  </list>
</section>

<section id="connect">
  <title>Ansluta till och initiera databasen</title>
  <p>Koden som skapar anslutningen till databasen är i metoden <code>setupDatabase</code> nedan:</p>
  <code mime="application/javascript" style="numbered">
  setupDatabase: function () {
    this.connection = new Gda.Connection ({provider: Gda.Config.get_provider("SQLite"),
                                          cnc_string:"DB_DIR=" + GLib.get_home_dir () + ";DB_NAME=gnome_demo"});
    this.connection.open ();

    try {
      var dm = this.connection.execute_select_command ("select * from demo");
    } catch (e) {
      this.connection.execute_non_select_command ("create table demo (id integer, name varchar(100))");
    }
  },</code>
  <list>
    <item>
      <p>Lines 2‒3: Create the GDA's <code>Connection</code> object. We must supply to its constructor some properties:</p>
      <list>
        <item>
          <p><code>provider</code>: One of GDA's supported providers. GDA supports SQLite, MySQL, PostgreSQL, Oracle and many others. For demo purposes we will use a SQLite database, as it comes installed by default in most distributions and it is simple to use (it just uses a file as a database).</p>
        </item>
        <item>
          <p><code>cnc_string</code>: The connection string. It may change from provider to provider. The syntax for SQLite is: <code>DB_DIR=<var>PATH</var>;DB_NAME=<var>FILENAME</var></code>. In this demo we are accessing a database called gnome_demo in the user home dir (note the call to GLib's <code>get_home_dir</code> function).</p>
        </item>
      </list>
      <note>
        <p>If the provider is not supported by GDA, or if the connection string is missing some element, line 2 will raise an exception. So, in real life we should handle it with JavaScript's statement <code>try</code>...<code>catch</code>.</p>
      </note>
    </item>

    <item><p>Line 4: Open the connection. In the SQLite provider, if the database does not exist, it will be created in this step.</p></item>
    <item>
      <p>Lines 6‒10: Try to do a simple select to check if the table exists (line 7). If it does not exist (because the database was just created), this command will raise an exception, which is handled by the <code>try</code>...<code>catch</code> block. If it is the case, we run the create table statement (line 9).</p>
      <p>In order to run the SQL commands above we are using the GDA connection methods <code>execute_select_command</code> and <code>execute_non_select_command</code>. They are simple to use, and just require two arguments: The <code>Connection</code> object and the SQL command to be parsed.</p>
    </item>
  </list>

  <p>Vid denna punkt har vi konfigurerat databasen, och är redo att använda den.</p>
</section>

<section id="select">
  <title>Selecting</title>
  <p>
     After connecting to the database, our demo's constructor calls the <code>selectData</code> method. It is responsible for getting all the records in the table and showing them on the <code>TextView</code> widget. Let's take a look at it:
  </p>
  <code mime="application/javascript" style="numbered">
  selectData: function () {
    var dm = this.connection.execute_select_command  ("select * from demo order by 1, 2");
    var iter = dm.create_iter ();

    var text = "";

    while (iter.move_next ()) {
      var id_field = Gda.value_stringify (iter.get_value_at (0));
      var name_field = Gda.value_stringify (iter.get_value_at (1));

      text += id_field + "\t=&gt;\t" + name_field + '\n';
    }

    this.text.buffer.text = text;
    this.count_label.label = "&lt;i&gt;" + dm.get_n_rows () + " record(s)&lt;/i&gt;";
  },</code>
  <list>
    <item><p>Line 2: The <code>SELECT</code> command. We are using the GDA connection's <code>execute_select_command</code> method for that. It returns a <code>DataModel</code> object, which is later used to retrieve the rows.</p></item>
    <item><p>Line 3: Create an <code>Iter</code> object, which is used to iterate over the <code>DataModel</code>'s records.</p></item>
    <item><p>Line 7: Loop through all the records, fetching them with the help of the <code>Iter</code> object. At this point, the <code>iter</code> variable contains the actual, retrieved data. Its <code>move_next</code> method returns <code>false</code> when it reaches the last record.</p></item>
    <item>
      <p>Lines 8‒9: We do two things in each line:</p>
      <list>
        <item><p>Use <code>Iter</code>'s method <code>get_value_at</code>, which requires only one argument: the column number to retrieve, starting at 0. As our <code>SELECT</code> command returns only two columns, we are retrieving columns 0 and 1.</p></item>
        <item><p>The method <code>get_value_at</code> returns the field in GLib's <code>GValue</code> format. A simple way to convert this format to a string is by using GDA's global function <code>value_stringify</code>. That's what we are doing here, and we store the results in the variables <code>id_field</code> and <code>name_field</code>.</p></item>
      </list>
    </item>
    <item><p>Line 11: Concatenate the two fields to make one text line, separated by <code>"=&gt;"</code>, and store it in the <code>text</code> variable.</p></item>
    <item><p>Line 14: After the loop is finished, we have all the records formatted in the <code>text</code> variable. In this line we just set the contents of the <code>TextView</code> with that variable.</p></item>
    <item><p>Line 15: Display the number of records in the table, making use of the <code>DataModel</code>'s <code>get_n_rows</code> method.</p></item>
  </list>
</section>

<section id="insert">
  <title>Inserting</title>
  <p>
     OK, we know how to connect to a database and how to select rows from a table. Now it's time to do an <code>INSERT</code> on the table. Do you remember above, in the method <code>setupWindow</code> we connected the <gui>Insert</gui> button's <code>clicked</code> signal to the method <code>_insertClicked</code>? Let's see the implementation of this method.
  </p>
  <code mime="application/javascript" style="numbered">
  _insertClicked: function () {
    if (!this._validateFields ())
      return;

    // Gda.execute_non_select_command (this.connection,
    //   "insert into demo values ('" + this.id_entry.text + "', '" + this.name_entry.text + "')");

    var b = new Gda.SqlBuilder ({stmt_type:Gda.SqlStatementType.INSERT});
    b.set_table ("demo");
    b.add_field_value_as_gvalue ("id", this.id_entry.text);
    b.add_field_value_as_gvalue ("name", this.name_entry.text);
    var stmt = b.get_statement ();
    this.connection.statement_execute_non_select (stmt, null);

    this._clearFields ();
    this.selectData ();
  },</code>
  <p>
    We have learned how to use the GDA connection's methods <code>execute_select_command</code> and <code>execute_non_select_command</code> to quickly execute SQL commands on the database. GDA allows one to build a SQL statement indirectly, by using its <code>SqlBuilder</code> object. What are the benefits of this? GDA will generate the SQL statement dynamically, and it will be valid for the connection provider used (it will use the same SQL dialect the provider uses). Let's study the code:
  </p>
  <list>
    <item><p>Lines 2‒3: Check if the user filled all the fields. The code for the private method <code>_validateFields</code> is really simple and you can read it in the full demo source code.</p></item>
    <item><p>Line 5: The faster way of doing the <code>INSERT</code>. It's commented out as we want to show how to use the <code>SqlBuilder</code> object to build a SQL statement portable across databases.</p></item>
    <item><p>Line 7: Create the <code>SqlBuilder</code> object. We must pass the type of statement we are going to build. It can be <code>SELECT</code>, <code>UPDATE</code>, <code>INSERT</code> or <code>DELETE</code>.</p></item>
    <item><p>Line 8: Set the name of the table on which the built statement will operate (it will generate <code>INSERT INTO demo</code>)</p></item>
    <item><p>Lines 9‒10: Set the fields and its values that will be part of the statement. The first argument is the field name (as in the table). The second one is the value for that field.</p></item>
    <item><p>Line 11: Get the dynamically generated <code>Statement</code> object, which represents a SQL statement.</p></item>
    <item><p>Rad 12: Exekvera slutligen SQL-satsen (<code>INSERT</code>).</p></item>
    <item><p>Line 14: Clear the id and name fields on the screen.  The code for the private method <code>_clearFields</code> is really simple and you can read it in the full demo source code.</p></item>
    <item><p>Line 15: Refresh the view on the screen by doing another <code>SELECT</code>.</p></item>
  </list>
  <note><p>You can also make use of parameters while building the statement. By using the <code>SqlBuilder</code> objects and parameters you are less subject to attacks like SQL injection. Check the <link href="http://library.gnome.org/devel/libgda/stable/">GDA documentation</link> for more information about parameters.</p></note>
</section>

<section id="run">
  <title>Kör programmet</title>
  <p>All kod som du behöver bör nu vara på plats, så testa att köra koden. Du har nu en databas för din skivsamling!</p>
</section>

<section id="impl">
 <title>Referensimplementation</title>
 <p>Om du stöter på problem med handledningen kan du jämföra din kod med denna <link href="record-collection/record-collection.js">referenskod</link>.</p>
</section>
</page>
