summaryrefslogtreecommitdiffstats
path: root/kspread/kspread_functions_database.cpp
blob: a294914d61502400d109d7008ccb90cc7da20a57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
/* This file is part of the KDE project
   Copyright (C) 1998-2002 The KSpread Team
                           www.koffice.org/kspread
   Copyright (C) 2005 Tomas Mecir <mecirt@gmail.com>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

// built-in database functions

#include "functions.h"
#include "valuecalc.h"
#include "valueconverter.h"

using namespace KSpread;

// prototypes
Value func_daverage (valVector args, ValueCalc *calc, FuncExtra *);
Value func_dcount (valVector args, ValueCalc *calc, FuncExtra *);
Value func_dcounta (valVector args, ValueCalc *calc, FuncExtra *);
Value func_dget (valVector args, ValueCalc *calc, FuncExtra *);
Value func_dmax (valVector args, ValueCalc *calc, FuncExtra *);
Value func_dmin (valVector args, ValueCalc *calc, FuncExtra *);
Value func_dproduct (valVector args, ValueCalc *calc, FuncExtra *);
Value func_dstdev (valVector args, ValueCalc *calc, FuncExtra *);
Value func_dstdevp (valVector args, ValueCalc *calc, FuncExtra *);
Value func_dsum (valVector args, ValueCalc *calc, FuncExtra *);
Value func_dvar (valVector args, ValueCalc *calc, FuncExtra *);
Value func_dvarp (valVector args, ValueCalc *calc, FuncExtra *);
Value func_getpivotdata (valVector args, ValueCalc *calc, FuncExtra *);

// registers all database functions
void RegisterDatabaseFunctions()
{
  FunctionRepository* repo = FunctionRepository::self();
  Function *f;

  f = new Function ("DAVERAGE",     func_daverage);
  f->setParamCount (3);
  f->setAcceptArray ();
  repo->add (f);
  f = new Function ("DCOUNT",       func_dcount);
  f->setParamCount (3);
  f->setAcceptArray ();
  repo->add (f);
  f = new Function ("DCOUNTA",      func_dcounta);
  f->setParamCount (3);
  f->setAcceptArray ();
  repo->add (f);
  f = new Function ("DGET",         func_dget);
  f->setParamCount (3);
  f->setAcceptArray ();
  repo->add (f);
  f = new Function ("DMAX",         func_dmax);
  f->setParamCount (3);
  f->setAcceptArray ();
  repo->add (f);
  f = new Function ("DMIN",         func_dmin);
  f->setParamCount (3);
  f->setAcceptArray ();
  repo->add (f);
  f = new Function ("DPRODUCT",     func_dproduct);
  f->setParamCount (3);
  f->setAcceptArray ();
  repo->add (f);
  f = new Function ("DSTDEV",       func_dstdev);
  f->setParamCount (3);
  f->setAcceptArray ();
  repo->add (f);
  f = new Function ("DSTDEVP",      func_dstdevp);
  f->setParamCount (3);
  f->setAcceptArray ();
  repo->add (f);
  f = new Function ("DSUM",         func_dsum);
  f->setParamCount (3);
  f->setAcceptArray ();
  repo->add (f);
  f = new Function ("DVAR",         func_dvar);
  f->setParamCount (3);
  f->setAcceptArray ();
  repo->add (f);
  f = new Function ("DVARP",        func_dvarp);
  f->setParamCount (3);
  f->setAcceptArray ();
  repo->add (f);
  f = new Function ("GETPIVOTDATA", func_getpivotdata); // partially Excel-compatible
  f->setParamCount (2);
  f->setAcceptArray ();
  repo->add (f);
}

int getFieldIndex (ValueCalc *calc, Value fieldName,
    Value database)
{
  if (fieldName.isNumber())
    return fieldName.asInteger() - 1;
  if (!fieldName.isString ())
    return -1;

  TQString fn = fieldName.asString();
  int cols = database.columns ();
  for (int i = 0; i < cols; ++i)
    if (fn.lower() ==
        calc->conv()->asString (database.element (i, 0)).asString().lower())
    return i;
  return -1;
}

// ***********************************************************
// *** DBConditions class - maintains an array of conditions ***
// ***********************************************************

class DBConditions {
 public:
  DBConditions (ValueCalc *vc, Value database, Value conds);
  ~DBConditions ();
  /** Does a specified row of the database match the given criteria?
  The row with column names is ignored - hence 0 specifies first data row. */
  bool matches (unsigned row);
 private:
  void parse (Value conds);
  ValueCalc *calc;
  Condition **cond;
  int rows, cols;
  Value db;
};

DBConditions::DBConditions (ValueCalc *vc, Value database,
    Value conds) : calc(vc), cond(0), rows(0), cols(0), db(database)
{
  parse (conds);
}

DBConditions::~DBConditions () {
  int count = rows*cols;
  for (int r = 0; r < count; ++r)
    delete cond[r];
  delete[] cond;
}

void DBConditions::parse (Value conds)
{
  // initialize the array
  rows = conds.rows() - 1;
  cols = db.columns();
  int count = rows*cols;
  cond = new Condition* [count];
  for (int r = 0; r < count; ++r)
    cond[r] = 0;

  // perform the parsing itself
  int cc = conds.columns ();
  for (int c = 0; c < cc; ++c)
  {
    // first row contains column names
    int col = getFieldIndex (calc, conds.element (c, 0), db);
    if (col < 0) continue;  // failed - ignore the column

    // fill in the conditions for a given column name
    for (int r = 0; r < rows; ++r) {
      Value cnd = conds.element (c, r+1);
      if (cnd.isEmpty()) continue;
      int idx = r * cols + col;
      if (cond[idx]) delete cond[idx];
      cond[idx] = new Condition;
      calc->getCond (*cond[idx], cnd);
    }
  }
}

bool DBConditions::matches (unsigned row)
{
  if (row >= db.rows() - 1)
    return false;    // out of range

  // we have a match, if at least one row of criteria matches
  for (int r = 0; r < rows; ++r) {
    // within a row, all criteria must match
    bool match = true;
    for (int c = 0; c < cols; ++c) {
      int idx = r * cols + c;
      if (!cond[idx]) continue;
      if (!calc->matches (*cond[idx], db.element (c, row + 1))) {
        match = false;  // didn't match
        break;
      }
    }
    if (match)  // all conditions in this row matched
      return true;
  }

  // no row matched
  return false;
}


// *******************************************
// *** Function implementations start here ***
// *******************************************

// Function: DSUM
Value func_dsum (valVector args, ValueCalc *calc, FuncExtra *)
{
  Value database = args[0];
  Value conditions = args[2];
  int fieldIndex = getFieldIndex (calc, args[1], database);
  if (fieldIndex < 0)
    return Value::errorVALUE();

  DBConditions conds (calc, database, conditions);

  int rows = database.rows() - 1;  // first row contains column names
  Value res( Value::Float );
  for (int r = 0; r < rows; ++r)
    if (conds.matches (r)) {
      Value val = database.element (fieldIndex, r + 1);
      // include this value in the result
      if (!val.isEmpty ())
        res = calc->add (res, val);
    }

  return res;
}

// Function: DAVERAGE
Value func_daverage (valVector args, ValueCalc *calc, FuncExtra *)
{
  Value database = args[0];
  Value conditions = args[2];
  int fieldIndex = getFieldIndex (calc, args[1], database);
  if (fieldIndex < 0)
    return Value::errorVALUE();

  DBConditions conds (calc, database, conditions);

  int rows = database.rows() - 1;  // first row contains column names
  Value res;
  int count = 0;
  for (int r = 0; r < rows; ++r)
    if (conds.matches (r)) {
      Value val = database.element (fieldIndex, r + 1);
      // include this value in the result
      if (!val.isEmpty ()) {
        res = calc->add (res, val);
        count++;
      }
    }
  if (count) res = calc->div (res, count);
  return res;
}

// Function: DCOUNT
Value func_dcount (valVector args, ValueCalc *calc, FuncExtra *)
{
  Value database = args[0];
  Value conditions = args[2];
  int fieldIndex = getFieldIndex (calc, args[1], database);
  if (fieldIndex < 0)
    return Value::errorVALUE();

  DBConditions conds (calc, database, conditions);

  int rows = database.rows() - 1;  // first row contains column names
  int count = 0;
  for (int r = 0; r < rows; ++r)
    if (conds.matches (r)) {
      Value val = database.element (fieldIndex, r + 1);
      // include this value in the result
      if ((!val.isEmpty()) && (!val.isBoolean()) && (!val.isString()))
        count++;
    }

  return Value (count);
}

// Function: DCOUNTA
Value func_dcounta (valVector args, ValueCalc *calc, FuncExtra *)
{
  Value database = args[0];
  Value conditions = args[2];
  int fieldIndex = getFieldIndex (calc, args[1], database);
  if (fieldIndex < 0)
    return Value::errorVALUE();

  DBConditions conds (calc, database, conditions);

  int rows = database.rows() - 1;  // first row contains column names
  int count = 0;
  for (int r = 0; r < rows; ++r)
    if (conds.matches (r)) {
      Value val = database.element (fieldIndex, r + 1);
      // include this value in the result
      if (!val.isEmpty())
        count++;
    }

  return Value (count);
}

// Function: DGET
Value func_dget (valVector args, ValueCalc *calc, FuncExtra *)
{
  Value database = args[0];
  Value conditions = args[2];
  int fieldIndex = getFieldIndex (calc, args[1], database);
  if (fieldIndex < 0)
    return Value::errorVALUE();

  DBConditions conds (calc, database, conditions);

  bool match = false;
  Value result = Value::errorVALUE();
  int rows = database.rows() - 1;  // first row contains column names
  for (int r = 0; r < rows; ++r)
    if (conds.matches (r)) {
      if (match) {
        // error on multiple matches
        result = Value::errorVALUE();
        break;
      }
      result = database.element (fieldIndex, r + 1);
      match = true;
    }

  return result;
}

// Function: DMAX
Value func_dmax (valVector args, ValueCalc *calc, FuncExtra *)
{
  Value database = args[0];
  Value conditions = args[2];
  int fieldIndex = getFieldIndex (calc, args[1], database);
  if (fieldIndex < 0)
    return Value::errorVALUE();

  DBConditions conds (calc, database, conditions);

  int rows = database.rows() - 1;  // first row contains column names
  Value res;
  bool got = false;
  for (int r = 0; r < rows; ++r)
    if (conds.matches (r)) {
      Value val = database.element (fieldIndex, r + 1);
      // include this value in the result
      if (!val.isEmpty ()) {
        if (!got) {
          res = val;
          got = true;
        }
        else
          if (calc->greater (val, res))
            res = val;
      }
    }

  return res;
}

// Function: DMIN
Value func_dmin (valVector args, ValueCalc *calc, FuncExtra *)
{
  Value database = args[0];
  Value conditions = args[2];
  int fieldIndex = getFieldIndex (calc, args[1], database);
  if (fieldIndex < 0)
    return Value::errorVALUE();

  DBConditions conds (calc, database, conditions);

  int rows = database.rows() - 1;  // first row contains column names
  Value res;
  bool got = false;
  for (int r = 0; r < rows; ++r)
    if (conds.matches (r)) {
      Value val = database.element (fieldIndex, r + 1);
      // include this value in the result
      if (!val.isEmpty ()) {
        if (!got) {
          res = val;
          got = true;
        }
        else
          if (calc->lower (val, res))
            res = val;
      }
    }

  return res;
}

// Function: DPRODUCT
Value func_dproduct (valVector args, ValueCalc *calc, FuncExtra *)
{
  Value database = args[0];
  Value conditions = args[2];
  int fieldIndex = getFieldIndex (calc, args[1], database);
  if (fieldIndex < 0)
    return Value::errorVALUE();

  DBConditions conds (calc, database, conditions);

  int rows = database.rows() - 1;  // first row contains column names
  Value res = 1.0;
  bool got = false;
  for (int r = 0; r < rows; ++r)
    if (conds.matches (r)) {
      Value val = database.element (fieldIndex, r + 1);
      // include this value in the result
      if (!val.isEmpty ()) {
        got = true;
        res = calc->mul (res, val);
      }
    }
  if (got)
    return res;
  return Value::errorVALUE ();
}

// Function: DSTDEV
Value func_dstdev (valVector args, ValueCalc *calc, FuncExtra *)
{
  // sqrt (dvar)
  return calc->sqrt (func_dvar (args, calc, 0));
}

// Function: DSTDEVP
Value func_dstdevp (valVector args, ValueCalc *calc, FuncExtra *)
{
  // sqrt (dvarp)
  return calc->sqrt (func_dvarp (args, calc, 0));
}

// Function: DVAR
Value func_dvar (valVector args, ValueCalc *calc, FuncExtra *)
{
  Value database = args[0];
  Value conditions = args[2];
  int fieldIndex = getFieldIndex (calc, args[1], database);
  if (fieldIndex < 0)
    return Value::errorVALUE();

  DBConditions conds (calc, database, conditions);

  int rows = database.rows() - 1;  // first row contains column names
  Value avg;
  int count = 0;
  for (int r = 0; r < rows; ++r)
    if (conds.matches (r)) {
      Value val = database.element (fieldIndex, r + 1);
      // include this value in the result
      if (!val.isEmpty ()) {
        avg = calc->add (avg, val);
        count++;
      }
    }
  if (count < 2) return Value::errorDIV0();
  avg = calc->div (avg, count);

  Value res;
  for (int r = 0; r < rows; ++r)
    if (conds.matches (r)) {
      Value val = database.element (fieldIndex, r + 1);
      // include this value in the result
      if (!val.isEmpty ())
        res = calc->add (res, calc->sqr (calc->sub (val, avg)));
    }

  // res / (count-1)
  return calc->div (res, count - 1);
}

// Function: DVARP
Value func_dvarp (valVector args, ValueCalc *calc, FuncExtra *)
{
  Value database = args[0];
  Value conditions = args[2];
  int fieldIndex = getFieldIndex (calc, args[1], database);
  if (fieldIndex < 0)
    return Value::errorVALUE();

  DBConditions conds (calc, database, conditions);

  int rows = database.rows() - 1;  // first row contains column names
  Value avg;
  int count = 0;
  for (int r = 0; r < rows; ++r)
    if (conds.matches (r)) {
      Value val = database.element (fieldIndex, r + 1);
      // include this value in the result
      if (!val.isEmpty ()) {
        avg = calc->add (avg, val);
        count++;
      }
    }
  if (count == 0) return Value::errorDIV0();
  avg = calc->div (avg, count);

  Value res;
  for (int r = 0; r < rows; ++r)
    if (conds.matches (r)) {
      Value val = database.element (fieldIndex, r + 1);
      // include this value in the result
      if (!val.isEmpty ())
        res = calc->add (res, calc->sqr (calc->sub (val, avg)));
    }

  // res / count
  return calc->div (res, count);
}

// Function: GETPIVOTDATA
// FIXME implement more things with this, see Excel !
Value func_getpivotdata (valVector args, ValueCalc *calc, FuncExtra *)
{
  Value database = args[0];
  int fieldIndex = getFieldIndex (calc, args[1], database);
  if (fieldIndex < 0)
    return Value::errorVALUE();
  // the row at the bottom
  int row = database.rows() - 1;

  return database.element (fieldIndex, row);
}