table.c 69.8 KB
Newer Older
1 2 3
/*
 * Implementation of the Microsoft Installer (msi.dll)
 *
4
 * Copyright 2002-2005 Mike McCormack for CodeWeavers
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20
 */

21
#include <stdarg.h>
22
#include <assert.h>
23 24

#define COBJMACROS
25 26 27
#define NONAMELESSUNION
#define NONAMELESSSTRUCT

28 29 30 31 32 33 34 35
#include "windef.h"
#include "winbase.h"
#include "winerror.h"
#include "msi.h"
#include "msiquery.h"
#include "objbase.h"
#include "objidl.h"
#include "winnls.h"
36
#include "msipriv.h"
37 38
#include "query.h"

39 40 41
#include "wine/debug.h"
#include "wine/unicode.h"

42
WINE_DEFAULT_DEBUG_CHANNEL(msidb);
43

44
#define MSITABLE_HASH_TABLE_SIZE 37
45
#define LONG_STR_BYTES 3
46 47 48 49 50 51 52 53

typedef struct tagMSICOLUMNHASHENTRY
{
    struct tagMSICOLUMNHASHENTRY *next;
    UINT value;
    UINT row;
} MSICOLUMNHASHENTRY;

54 55
typedef struct tagMSICOLUMNINFO
{
56
    LPWSTR tablename;
57
    UINT   number;
58
    LPWSTR colname;
59 60
    UINT   type;
    UINT   offset;
61
    INT    ref_count;
62
    MSICOLUMNHASHENTRY **hash_table;
63 64
} MSICOLUMNINFO;

65 66 67 68 69 70 71
typedef struct tagMSIORDERINFO
{
    UINT *reorder;
    UINT num_cols;
    UINT cols[1];
} MSIORDERINFO;

72 73
struct tagMSITABLE
{
74
    BYTE **data;
75
    UINT row_count;
76
    BYTE **nonpersistent_data;
77
    UINT nonpersistent_row_count;
78
    struct list entry;
79 80
    MSICOLUMNINFO *colinfo;
    UINT col_count;
81
    BOOL persistent;
82
    INT ref_count;
83
    WCHAR name[1];
84
};
85

86 87 88 89 90
typedef struct tagMSITRANSFORM {
    struct list entry;
    IStorage *stg;
} MSITRANSFORM;

91 92 93 94 95
static const WCHAR szStringData[] = {
    '_','S','t','r','i','n','g','D','a','t','a',0 };
static const WCHAR szStringPool[] = {
    '_','S','t','r','i','n','g','P','o','o','l',0 };

96
/* information for default tables */
97 98 99 100 101 102
static WCHAR szTables[]  = { '_','T','a','b','l','e','s',0 };
static WCHAR szTable[]  = { 'T','a','b','l','e',0 };
static WCHAR szName[]    = { 'N','a','m','e',0 };
static WCHAR szColumns[] = { '_','C','o','l','u','m','n','s',0 };
static WCHAR szNumber[]  = { 'N','u','m','b','e','r',0 };
static WCHAR szType[]    = { 'T','y','p','e',0 };
103

104
static const MSICOLUMNINFO _Columns_cols[4] = {
105 106 107 108
    { szColumns, 1, szTable,  MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, NULL },
    { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2,     2, 0, NULL },
    { szColumns, 3, szName,   MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, NULL },
    { szColumns, 4, szType,   MSITYPE_VALID | 2,                   6, 0, NULL },
109
};
110 111

static const MSICOLUMNINFO _Tables_cols[1] = {
112
    { szTables,  1, szName,   MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, NULL },
113 114
};

115 116
#define MAX_STREAM_NAME 0x1f

117 118
static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name,
       MSICOLUMNINFO **pcols, UINT *pcount );
119 120
static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo,
       DWORD count );
121
static UINT get_tablecolumns( MSIDATABASE *db,
122
       LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz);
123
static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count );
124

125
static inline UINT bytes_per_column( MSIDATABASE *db, const MSICOLUMNINFO *col )
126
{
127 128
    if( MSITYPE_IS_BINARY(col->type) )
        return 2;
129
    if( col->type & MSITYPE_STRING )
130
        return db->bytes_per_strref;
131 132 133 134 135
    if( (col->type & 0xff) > 4 )
        ERR("Invalid column size!\n");
    return col->type & 0xff;
}

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
static int utf2mime(int x)
{
    if( (x>='0') && (x<='9') )
        return x-'0';
    if( (x>='A') && (x<='Z') )
        return x-'A'+10;
    if( (x>='a') && (x<='z') )
        return x-'a'+10+26;
    if( x=='.' )
        return 10+26+26;
    if( x=='_' )
        return 10+26+26+1;
    return -1;
}

151
static LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
152 153 154
{
    DWORD count = MAX_STREAM_NAME;
    DWORD ch, next;
155 156 157
    LPWSTR out, p;

    if( !bTable )
158
        count = lstrlenW( in )+2;
159
    out = msi_alloc( count*sizeof(WCHAR) );
160
    p = out;
161 162 163

    if( bTable )
    {
164
         *p++ = 0x4840;
165 166 167 168 169 170 171
         count --;
    }
    while( count -- ) 
    {
        ch = *in++;
        if( !ch )
        {
172 173
            *p = ch;
            return out;
174 175 176 177 178 179 180 181
        }
        if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
        {
            ch = utf2mime(ch) + 0x4800;
            next = *in;
            if( next && (next<0x80) )
            {
                next = utf2mime(next);
182
                if( next != -1 )
183 184 185 186 187 188 189
                {
                     next += 0x3ffffc0;
                     ch += (next<<6);
                     in++;
                }
            }
        }
190
        *p++ = ch;
191
    }
192
    ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
193
    msi_free( out );
194
    return NULL;
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
}

static int mime2utf(int x)
{
    if( x<10 )
        return x + '0';
    if( x<(10+26))
        return x - 10 + 'A';
    if( x<(10+26+26))
        return x - 10 - 26 + 'a';
    if( x == (10+26+26) )
        return '.';
    return '_';
}

210
BOOL decode_streamname(LPCWSTR in, LPWSTR out)
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
{
    WCHAR ch;
    DWORD count = 0;

    while ( (ch = *in++) )
    {
        if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
        {
            if( ch >= 0x4800 )
                ch = mime2utf(ch-0x4800);
            else
            {
                ch -= 0x3800;
                *out++ = mime2utf(ch&0x3f);
                count++;
                ch = mime2utf((ch>>6)&0x3f);
            }
        }
        *out++ = ch;
        count++;
    }
    *out = 0;
    return count;
}
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

void enum_stream_names( IStorage *stg )
{
    IEnumSTATSTG *stgenum = NULL;
    HRESULT r;
    STATSTG stat;
    ULONG n, count;
    WCHAR name[0x40];

    r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
    if( FAILED( r ) )
        return;

    n = 0;
    while( 1 )
    {
        count = 0;
        r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
        if( FAILED( r ) || !count )
            break;
        decode_streamname( stat.pwcsName, name );
256
        TRACE("stream %2d -> %s %s\n", n,
257
              debugstr_w(stat.pwcsName), debugstr_w(name) );
258
        CoTaskMemFree( stat.pwcsName );
259 260 261 262 263 264
        n++;
    }

    IEnumSTATSTG_Release( stgenum );
}

265
UINT read_stream_data( IStorage *stg, LPCWSTR stname, BOOL table,
266
                       BYTE **pdata, UINT *psz )
267 268 269 270 271
{
    HRESULT r;
    UINT ret = ERROR_FUNCTION_FAILED;
    VOID *data;
    ULONG sz, count;
272 273
    IStream *stm = NULL;
    STATSTG stat;
274
    LPWSTR encname;
275

276
    encname = encode_streamname(table, stname);
277 278

    TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
279

280
    r = IStorage_OpenStream(stg, encname, NULL, 
281
            STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
282
    msi_free( encname );
283 284
    if( FAILED( r ) )
    {
285
        WARN("open stream failed r = %08x - empty table?\n", r);
286
        return ret;
287 288 289 290 291
    }

    r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
    if( FAILED( r ) )
    {
292
        WARN("open stream failed r = %08x!\n", r);
293 294 295 296 297
        goto end;
    }

    if( stat.cbSize.QuadPart >> 32 )
    {
298
        WARN("Too big!\n");
299 300 301 302
        goto end;
    }
        
    sz = stat.cbSize.QuadPart;
303
    data = msi_alloc( sz );
304 305
    if( !data )
    {
306
        WARN("couldn't allocate memory r=%08x!\n", r);
307
        ret = ERROR_NOT_ENOUGH_MEMORY;
308 309 310 311
        goto end;
    }
        
    r = IStream_Read(stm, data, sz, &count );
312
    if( FAILED( r ) || ( count != sz ) )
313
    {
314
        msi_free( data );
315
        WARN("read stream failed r = %08x!\n", r);
316 317 318
        goto end;
    }

319 320 321
    *pdata = data;
    *psz = sz;
    ret = ERROR_SUCCESS;
322 323

end:
324
    IStream_Release( stm );
325 326 327 328

    return ret;
}

329
static UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
330
{
331
    LPWSTR encname;
332 333
    HRESULT r;

334
    encname = encode_streamname(FALSE, stname);
335 336 337 338 339 340 341

    TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));

    r = IStorage_OpenStream(db->storage, encname, NULL, 
            STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm);
    if( FAILED( r ) )
    {
342 343 344 345 346 347 348 349 350 351
        MSITRANSFORM *transform;

        LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
        {
            TRACE("looking for %s in transform storage\n", debugstr_w(stname) );
            r = IStorage_OpenStream( transform->stg, encname, NULL, 
                    STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
            if (SUCCEEDED(r))
                break;
        }
352 353
    }

354 355 356
    msi_free( encname );

    return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
357 358
}

359
UINT read_raw_stream_data( MSIDATABASE *db, LPCWSTR stname,
360 361 362 363 364 365 366 367 368
                              USHORT **pdata, UINT *psz )
{
    HRESULT r;
    UINT ret = ERROR_FUNCTION_FAILED;
    VOID *data;
    ULONG sz, count;
    IStream *stm = NULL;
    STATSTG stat;

369
    r = db_get_raw_stream( db, stname, &stm );
370
    if( r != ERROR_SUCCESS)
371
        return ret;
372 373 374
    r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
    if( FAILED( r ) )
    {
375
        WARN("open stream failed r = %08x!\n", r);
376 377 378 379 380
        goto end;
    }

    if( stat.cbSize.QuadPart >> 32 )
    {
381
        WARN("Too big!\n");
382 383 384 385
        goto end;
    }
        
    sz = stat.cbSize.QuadPart;
386
    data = msi_alloc( sz );
387 388
    if( !data )
    {
389
        WARN("couldn't allocate memory r=%08x!\n", r);
390 391 392 393 394 395 396
        ret = ERROR_NOT_ENOUGH_MEMORY;
        goto end;
    }
        
    r = IStream_Read(stm, data, sz, &count );
    if( FAILED( r ) || ( count != sz ) )
    {
397
        msi_free( data );
398
        WARN("read stream failed r = %08x!\n", r);
399 400 401 402 403 404 405 406 407 408 409 410 411
        goto end;
    }

    *pdata = data;
    *psz = sz;
    ret = ERROR_SUCCESS;

end:
    IStream_Release( stm );

    return ret;
}

412
UINT write_stream_data( IStorage *stg, LPCWSTR stname,
413
                        LPCVOID data, UINT sz, BOOL bTable )
414 415 416 417 418 419 420
{
    HRESULT r;
    UINT ret = ERROR_FUNCTION_FAILED;
    ULONG count;
    IStream *stm = NULL;
    ULARGE_INTEGER size;
    LARGE_INTEGER pos;
421
    LPWSTR encname;
422

423
    encname = encode_streamname(bTable, stname );
424
    r = IStorage_OpenStream( stg, encname, NULL, 
425
            STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
426 427 428 429 430
    if( FAILED(r) )
    {
        r = IStorage_CreateStream( stg, encname,
                STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
    }
431
    msi_free( encname );
432 433
    if( FAILED( r ) )
    {
434
        WARN("open stream failed r = %08x\n", r);
435 436 437 438 439
        return ret;
    }

    size.QuadPart = sz;
    r = IStream_SetSize( stm, size );
440
    if( FAILED( r ) )
441
    {
442
        WARN("Failed to SetSize\n");
443 444 445 446 447
        goto end;
    }

    pos.QuadPart = 0;
    r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
448
    if( FAILED( r ) )
449
    {
450
        WARN("Failed to Seek\n");
451 452 453
        goto end;
    }

454
    if (sz)
455
    {
456 457 458 459 460 461
        r = IStream_Write(stm, data, sz, &count );
        if( FAILED( r ) || ( count != sz ) )
        {
            WARN("Failed to Write\n");
            goto end;
        }
462 463 464 465 466 467 468 469 470 471
    }

    ret = ERROR_SUCCESS;

end:
    IStream_Release( stm );

    return ret;
}

472 473
static void free_table( MSITABLE *table )
{
474
    UINT i;
475
    for( i=0; i<table->row_count; i++ )
476 477
        msi_free( table->data[i] );
    msi_free( table->data );
478 479 480
    for( i=0; i<table->nonpersistent_row_count; i++ )
        msi_free( table->nonpersistent_data[i] );
    msi_free( table->nonpersistent_data );
481 482
    msi_free_colinfo( table->colinfo, table->col_count );
    msi_free( table->colinfo );
483
    msi_free( table );
484 485
}

486 487
static UINT msi_table_get_row_size( MSIDATABASE *db,const MSICOLUMNINFO *cols,
                                    UINT count )
488 489 490 491
{
    const MSICOLUMNINFO *last_col = &cols[count-1];
    if (!count)
        return 0;
492
    return last_col->offset + bytes_per_column( db, last_col );
493 494
}

495
/* add this table to the list of cached tables in the database */
496
static UINT read_table_from_storage( MSIDATABASE *db, MSITABLE *t, IStorage *stg )
497
{
498
    BYTE *rawdata = NULL;
499
    UINT rawsize = 0, i, j, row_size = 0;
500

501
    TRACE("%s\n",debugstr_w(t->name));
502

503
    row_size = msi_table_get_row_size( db, t->colinfo, t->col_count );
504 505

    /* if we can't read the table, just assume that it's empty */
506
    read_stream_data( stg, t->name, TRUE, &rawdata, &rawsize );
507
    if( !rawdata )
508
        return ERROR_SUCCESS;
509 510 511 512 513

    TRACE("Read %d bytes\n", rawsize );

    if( rawsize % row_size )
    {
514
        WARN("Table size is invalid %d/%d\n", rawsize, row_size );
Mike McCormack's avatar
Mike McCormack committed
515
        goto err;
516 517 518
    }

    t->row_count = rawsize / row_size;
519
    t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
520
    if( !t->data )
521
        goto err;
522 523

    /* transpose all the data */
James Hawkins's avatar
James Hawkins committed
524
    TRACE("Transposing data from %d rows\n", t->row_count );
525 526
    for( i=0; i<t->row_count; i++ )
    {
527
        t->data[i] = msi_alloc( row_size );
528
        if( !t->data[i] )
529
            goto err;
Mike McCormack's avatar
Mike McCormack committed
530

531
        for( j=0; j<t->col_count; j++ )
532
        {
533
            UINT ofs = t->colinfo[j].offset;
534
            UINT n = bytes_per_column( db, &t->colinfo[j] );
535
            UINT k;
536

537
            if ( n != 2 && n != 3 && n != 4 )
538 539
            {
                ERR("oops - unknown column width %d\n", n);
540
                goto err;
541
            }
542

543 544
            for ( k = 0; k < n; k++ )
                t->data[i][ofs + k] = rawdata[ofs*t->row_count + i * n + k];
545 546 547
        }
    }

548
    msi_free( rawdata );
549
    return ERROR_SUCCESS;
550
err:
551
    msi_free( rawdata );
552
    return ERROR_FUNCTION_FAILED;
553 554 555 556
}

void free_cached_tables( MSIDATABASE *db )
{
557
    while( !list_empty( &db->tables ) )
558
    {
559
        MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
560

561
        list_remove( &t->entry );
Mike McCormack's avatar
Mike McCormack committed
562
        free_table( t );
563 564 565
    }
}

566
static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
567 568 569
{
    MSITABLE *t;

570
    LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
571
        if( !lstrcmpW( name, t->name ) )
Mike McCormack's avatar
Mike McCormack committed
572
            return t;
573

Mike McCormack's avatar
Mike McCormack committed
574
    return NULL;
575 576
}

577 578
static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
{
579
    UINT r, column_count = 0;
580 581 582 583 584 585 586 587
    MSICOLUMNINFO *columns;

    /* get the number of columns in this table */
    column_count = 0;
    r = get_tablecolumns( db, name, NULL, &column_count );
    if( r != ERROR_SUCCESS )
        return r;

588 589
    *pcount = column_count;

590 591 592 593 594 595
    /* if there's no columns, there's no table */
    if( column_count == 0 )
        return ERROR_INVALID_PARAMETER;

    TRACE("Table %s found\n", debugstr_w(name) );

596
    columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO) );
597 598 599 600 601 602
    if( !columns )
        return ERROR_FUNCTION_FAILED;

    r = get_tablecolumns( db, name, columns, &column_count );
    if( r != ERROR_SUCCESS )
    {
603
        msi_free( columns );
604 605 606 607 608 609 610 611
        return ERROR_FUNCTION_FAILED;
    }

    *pcols = columns;

    return r;
}

612 613 614 615 616 617 618
UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
                       BOOL persistent, MSITABLE **table_ret)
{
    UINT r, nField;
    MSIVIEW *tv = NULL;
    MSIRECORD *rec = NULL;
    column_info *col;
619 620
    MSITABLE *table;
    UINT i;
621 622 623

    /* only add tables that don't exist already */
    if( TABLE_Exists(db, name ) )
624 625
    {
        WARN("table %s exists\n", debugstr_w(name));
626
        return ERROR_BAD_QUERY_SYNTAX;
627
    }
628

629 630 631 632
    table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
    if( !table )
        return ERROR_FUNCTION_FAILED;

633
    table->ref_count = 1;
634 635
    table->row_count = 0;
    table->data = NULL;
636 637
    table->nonpersistent_row_count = 0;
    table->nonpersistent_data = NULL;
638 639
    table->colinfo = NULL;
    table->col_count = 0;
640
    table->persistent = persistent;
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
    lstrcpyW( table->name, name );

    for( col = col_info; col; col = col->next )
        table->col_count++;

    table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
    if (!table->colinfo)
    {
        free_table( table );
        return ERROR_FUNCTION_FAILED;
    }

    for( i = 0, col = col_info; col; i++, col = col->next )
    {
        table->colinfo[ i ].tablename = strdupW( col->table );
        table->colinfo[ i ].number = i + 1;
        table->colinfo[ i ].colname = strdupW( col->column );
        table->colinfo[ i ].type = col->type;
        table->colinfo[ i ].offset = 0;
660
        table->colinfo[ i ].ref_count = 0;
661 662
        table->colinfo[ i ].hash_table = NULL;
    }
663
    table_calc_column_offsets( db, table->colinfo, table->col_count);
664

665 666 667
    r = TABLE_CreateView( db, szTables, &tv );
    TRACE("CreateView returned %x\n", r);
    if( r )
668 669
    {
        free_table( table );
670
        return r;
671
    }
672 673 674 675 676 677 678 679 680 681 682 683 684 685

    r = tv->ops->execute( tv, 0 );
    TRACE("tv execute returned %x\n", r);
    if( r )
        goto err;

    rec = MSI_CreateRecord( 1 );
    if( !rec )
        goto err;

    r = MSI_RecordSetStringW( rec, 1, name );
    if( r )
        goto err;

686
    r = tv->ops->insert_row( tv, rec, !persistent );
687 688 689 690 691 692 693 694
    TRACE("insert_row returned %x\n", r);
    if( r )
        goto err;

    tv->ops->delete( tv );
    tv = NULL;

    msiobj_release( &rec->hdr );
695
    rec = NULL;
696

697
    if( persistent )
698
    {
699 700
        /* add each column to the _Columns table */
        r = TABLE_CreateView( db, szColumns, &tv );
701
        if( r )
702
            return r;
703

704 705
        r = tv->ops->execute( tv, 0 );
        TRACE("tv execute returned %x\n", r);
706 707 708
        if( r )
            goto err;

709 710
        rec = MSI_CreateRecord( 4 );
        if( !rec )
711 712
            goto err;

713
        r = MSI_RecordSetStringW( rec, 1, name );
714 715 716
        if( r )
            goto err;

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
        /*
         * need to set the table, column number, col name and type
         * for each column we enter in the table
         */
        nField = 1;
        for( col = col_info; col; col = col->next )
        {
            r = MSI_RecordSetInteger( rec, 2, nField );
            if( r )
                goto err;

            r = MSI_RecordSetStringW( rec, 3, col->column );
            if( r )
                goto err;

            r = MSI_RecordSetInteger( rec, 4, col->type );
            if( r )
                goto err;

            r = tv->ops->insert_row( tv, rec, FALSE );
            if( r )
                goto err;

            nField++;
        }
        if( !col )
            r = ERROR_SUCCESS;
744 745 746 747 748 749 750 751 752 753
    }

err:
    if (rec)
        msiobj_release( &rec->hdr );
    /* FIXME: remove values from the string table on error */
    if( tv )
        tv->ops->delete( tv );

    if (r == ERROR_SUCCESS)
754 755 756 757 758 759 760
    {
        list_add_head( &db->tables, &table->entry );
        *table_ret = table;
    }
    else
        free_table( table );

761 762 763
    return r;
}

764
static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
765
{
Mike McCormack's avatar
Mike McCormack committed
766
    MSITABLE *table;
767
    UINT r;
768 769

    /* first, see if the table is cached */
Mike McCormack's avatar
Mike McCormack committed
770 771
    table = find_cached_table( db, name );
    if( table )
772 773 774 775
    {
        *table_ret = table;
        return ERROR_SUCCESS;
    }
776

777 778 779 780
    /* nonexistent tables should be interpreted as empty tables */
    table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
    if( !table )
        return ERROR_FUNCTION_FAILED;
781

782 783
    table->row_count = 0;
    table->data = NULL;
784 785
    table->nonpersistent_row_count = 0;
    table->nonpersistent_data = NULL;
786 787
    table->colinfo = NULL;
    table->col_count = 0;
788
    table->persistent = TRUE;
789 790
    lstrcpyW( table->name, name );

791 792
    r = table_get_column_info( db, name, &table->colinfo, &table->col_count);
    if (r != ERROR_SUCCESS)
793
    {
794 795
        free_table ( table );
        return r;
796 797
    }

798
    r = read_table_from_storage( db, table, db->storage );
799 800 801 802 803 804 805 806 807
    if( r != ERROR_SUCCESS )
    {
        free_table( table );
        return r;
    }

    list_add_head( &db->tables, &table->entry );
    *table_ret = table;
    return ERROR_SUCCESS;
808 809
}

810
static UINT save_table( MSIDATABASE *db, const MSITABLE *t )
811
{
812
    BYTE *rawdata = NULL, *p;
813
    UINT rawsize, r, i, j, row_size;
814

815 816 817 818
    /* Nothing to do for non-persistent tables */
    if( !t->persistent )
        return ERROR_SUCCESS;

819 820
    TRACE("Saving %s\n", debugstr_w( t->name ) );

821
    row_size = msi_table_get_row_size( db, t->colinfo, t->col_count );
822 823

    rawsize = t->row_count * row_size;
824
    rawdata = msi_alloc_zero( rawsize );
825
    if( !rawdata )
826 827 828 829
    {
        r = ERROR_NOT_ENOUGH_MEMORY;
        goto err;
    }
830 831

    p = rawdata;
832
    for( i=0; i<t->col_count; i++ )
833 834 835
    {
        for( j=0; j<t->row_count; j++ )
        {
836
            UINT offset = t->colinfo[i].offset;
837

838 839
            *p++ = t->data[j][offset];
            *p++ = t->data[j][offset + 1];
840
            if( 4 == bytes_per_column( db, &t->colinfo[i] ) )
841 842 843 844
            {
                *p++ = t->data[j][offset + 2];
                *p++ = t->data[j][offset + 3];
            }
845 846 847 848
        }
    }

    TRACE("writing %d bytes\n", rawsize);
849
    r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
850

851
err:
852
    msi_free( rawdata );
853 854 855 856

    return r;
}

857 858
static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo,
                                       DWORD count )
859 860 861 862 863 864 865 866
{
    DWORD i;

    for( i=0; colinfo && (i<count); i++ )
    {
         assert( (i+1) == colinfo[ i ].number );
         if (i)
             colinfo[i].offset = colinfo[ i - 1 ].offset
867
                               + bytes_per_column( db, &colinfo[ i - 1 ] );
868 869 870 871 872 873 874 875
         else
             colinfo[i].offset = 0;
         TRACE("column %d is [%s] with type %08x ofs %d\n",
               colinfo[i].number, debugstr_w(colinfo[i].colname),
               colinfo[i].type, colinfo[i].offset);
    }
}

876 877
static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name,
                                     MSICOLUMNINFO *colinfo, UINT *sz)
878
{
879 880 881 882
    const MSICOLUMNINFO *p;
    DWORD i, n;

    TRACE("%s\n", debugstr_w(name));
883

884
    if (!lstrcmpW( name, szTables ))
885
    {
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
        p = _Tables_cols;
        n = 1;
    }
    else if (!lstrcmpW( name, szColumns ))
    {
        p = _Columns_cols;
        n = 4;
    }
    else
        return ERROR_FUNCTION_FAILED;

    /* duplicate the string data so we can free it in msi_free_colinfo */
    for (i=0; i<n; i++)
    {
        if (colinfo && (i < *sz) )
901
        {
902
            colinfo[i] = p[i];
903 904
            colinfo[i].tablename = strdupW( p[i].tablename );
            colinfo[i].colname = strdupW( p[i].colname );
905
        }
906
        if( colinfo && (i >= *sz) )
907 908
            break;
    }
909
    table_calc_column_offsets( db, colinfo, n );
910 911 912 913
    *sz = n;
    return ERROR_SUCCESS;
}

914 915 916 917 918 919
static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
{
    UINT i;

    for( i=0; i<count; i++ )
    {
920 921
        msi_free( colinfo[i].tablename );
        msi_free( colinfo[i].colname );
922
        msi_free( colinfo[i].hash_table );
923 924 925
    }
}

926
static LPWSTR msi_makestring( const MSIDATABASE *db, UINT stringid)
927
{
928
    return strdupW(msi_string_lookup_id( db->strings, stringid ));
929 930
}

931
static UINT read_table_int(BYTE *const *data, UINT row, UINT col, UINT bytes)
932 933 934
{
    UINT ret = 0, i;

935 936
    for (i = 0; i < bytes; i++)
        ret += (data[row][col + i] << i * 8);
937 938 939 940

    return ret;
}

941
static UINT get_tablecolumns( MSIDATABASE *db,
942 943 944 945 946
       LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
{
    UINT r, i, n=0, table_id, count, maxcount = *sz;
    MSITABLE *table = NULL;

947
    TRACE("%s\n", debugstr_w(szTableName));
948

949
    /* first check if there is a default table with that name */
950
    r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
951 952 953
    if( ( r == ERROR_SUCCESS ) && *sz )
        return r;

954 955
    r = get_table( db, szColumns, &table );
    if( r != ERROR_SUCCESS )
956
    {
957
        ERR("couldn't load _Columns table\n");
Mike McCormack's avatar
Mike McCormack committed
958
        return ERROR_FUNCTION_FAILED;
959 960 961
    }

    /* convert table and column names to IDs from the string table */
962
    r = msi_string2idW( db->strings, szTableName, &table_id );
963 964
    if( r != ERROR_SUCCESS )
    {
965
        WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
966 967 968
        return r;
    }

969
    TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
970

971 972
    /* Note: _Columns table doesn't have non-persistent data */

973 974
    /* if maxcount is non-zero, assume it's exactly right for this table */
    memset( colinfo, 0, maxcount*sizeof(*colinfo) );
975
    count = table->row_count;
976 977
    for( i=0; i<count; i++ )
    {
978
        if( read_table_int(table->data, i, 0, db->bytes_per_strref) != table_id )
979 980 981
            continue;
        if( colinfo )
        {
982 983
            UINT id = read_table_int(table->data, i, table->colinfo[2].offset, db->bytes_per_strref);
            UINT col = read_table_int(table->data, i, table->colinfo[1].offset, sizeof(USHORT)) - (1<<15);
984 985 986 987 988 989 990 991 992 993

            /* check the column number is in range */
            if (col<1 || col>maxcount)
            {
                ERR("column %d out of range\n", col);
                continue;
            }

            /* check if this column was already set */
            if (colinfo[ col - 1 ].number)
994
            {
995 996
                ERR("duplicate column %d\n", col);
                continue;
997
            }
998 999 1000 1001

            colinfo[ col - 1 ].tablename = msi_makestring( db, table_id );
            colinfo[ col - 1 ].number = col;
            colinfo[ col - 1 ].colname = msi_makestring( db, id );
1002 1003 1004
            colinfo[ col - 1 ].type = read_table_int(table->data, i,
                                                     table->colinfo[3].offset,
                                                     sizeof(USHORT)) - (1<<15);
1005
            colinfo[ col - 1 ].offset = 0;
1006
            colinfo[ col - 1 ].ref_count = 0;
1007
            colinfo[ col - 1 ].hash_table = NULL;
1008 1009
        }
        n++;
1010 1011 1012 1013
    }

    TRACE("%s has %d columns\n", debugstr_w(szTableName), n);

1014
    if (colinfo && n != maxcount)
1015 1016 1017 1018 1019 1020
    {
        ERR("missing column in table %s\n", debugstr_w(szTableName));
        msi_free_colinfo(colinfo, maxcount );
        return ERROR_FUNCTION_FAILED;
    }

1021
    table_calc_column_offsets( db, colinfo, n );
1022 1023 1024 1025 1026
    *sz = n;

    return ERROR_SUCCESS;
}

1027 1028 1029
static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
{
    MSITABLE *table;
1030
    UINT size, offset, old_count;
1031
    UINT n;
1032 1033

    table = find_cached_table( db, name );
1034
    old_count = table->col_count;
1035 1036 1037
    msi_free( table->colinfo );
    table_get_column_info( db, name, &table->colinfo, &table->col_count );

1038 1039 1040
    if (!table->col_count)
        return;

1041
    size = msi_table_get_row_size( db, table->colinfo, table->col_count );
1042 1043 1044 1045 1046
    offset = table->colinfo[table->col_count - 1].offset;

    for ( n = 0; n < table->row_count; n++ )
    {
        table->data[n] = msi_realloc( table->data[n], size );
1047 1048
        if (old_count < table->col_count)
            memset( &table->data[n][offset], 0, size - offset );
1049 1050 1051
    }
}

1052
/* try to find the table name in the _Tables table */
1053
BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
1054 1055 1056 1057 1058 1059 1060 1061 1062
{
    UINT r, table_id = 0, i, count;
    MSITABLE *table = NULL;

    if( !lstrcmpW( name, szTables ) )
        return TRUE;
    if( !lstrcmpW( name, szColumns ) )
        return TRUE;

1063
    r = msi_string2idW( db->strings, name, &table_id );
1064 1065
    if( r != ERROR_SUCCESS )
    {
1066
        TRACE("Couldn't find id for %s\n", debugstr_w(name));
1067 1068 1069
        return FALSE;
    }

1070 1071
    r = get_table( db, szTables, &table );
    if( r != ERROR_SUCCESS )
1072
    {
1073
        ERR("table %s not available\n", debugstr_w(szTables));
1074 1075 1076
        return FALSE;
    }

1077
    count = table->row_count;
1078
    for( i=0; i<count; i++ )
1079
        if( table->data[ i ][ 0 ] == table_id )
1080
            return TRUE;
1081

1082 1083 1084
    count = table->nonpersistent_row_count;
    for( i=0; i<count; i++ )
        if( table->nonpersistent_data[ i ][ 0 ] == table_id )
1085
            return TRUE;
1086

1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    return FALSE;
}

/* below is the query interface to a table */

typedef struct tagMSITABLEVIEW
{
    MSIVIEW        view;
    MSIDATABASE   *db;
    MSITABLE      *table;
    MSICOLUMNINFO *columns;
1098
    MSIORDERINFO  *order;
1099 1100 1101 1102 1103 1104 1105 1106
    UINT           num_cols;
    UINT           row_size;
    WCHAR          name[1];
} MSITABLEVIEW;

static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1107
    UINT offset, n;
1108
    BYTE **data;
1109 1110 1111 1112 1113 1114 1115 1116

    if( !tv->table )
        return ERROR_INVALID_PARAMETER;

    if( (col==0) || (col>tv->num_cols) )
        return ERROR_INVALID_PARAMETER;

    /* how many rows are there ? */
1117
    if( row >= tv->table->row_count + tv->table->nonpersistent_row_count )
1118 1119 1120 1121 1122 1123 1124 1125 1126
        return ERROR_NO_MORE_ITEMS;

    if( tv->columns[col-1].offset >= tv->row_size )
    {
        ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
        ERR("%p %p\n", tv, tv->columns );
        return ERROR_FUNCTION_FAILED;
    }

1127 1128 1129
    if (tv->order)
        row = tv->order->reorder[row];

1130 1131 1132 1133 1134 1135 1136
    if (row >= tv->table->row_count)
    {
        row -= tv->table->row_count;
        data = tv->table->nonpersistent_data;
    }
    else
        data = tv->table->data;
1137

1138
    n = bytes_per_column( tv->db, &tv->columns[col-1] );
1139
    if (n != 2 && n != 3 && n != 4)
1140 1141 1142 1143 1144
    {
        ERR("oops! what is %d bytes per column?\n", n );
        return ERROR_FUNCTION_FAILED;
    }

1145
    offset = tv->columns[col-1].offset;
1146 1147
    *val = read_table_int(data, row, offset, n);

1148
    /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1149 1150 1151 1152

    return ERROR_SUCCESS;
}

1153 1154 1155 1156 1157 1158 1159 1160 1161
/*
 * We need a special case for streams, as we need to reference column with
 * the name of the stream in the same table, and the table name
 * which may not be available at higher levels of the query
 */
static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    UINT ival = 0, refcol = 0, r;
1162
    LPCWSTR sval;
1163 1164 1165
    LPWSTR full_name;
    DWORD len;
    static const WCHAR szDot[] = { '.', 0 };
1166
    WCHAR number[0x20];
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180

    if( !view->ops->fetch_int )
        return ERROR_INVALID_PARAMETER;

    /*
     * The column marked with the type stream data seems to have a single number
     * which references the column containing the name of the stream data
     *
     * Fetch the column to reference first.
     */
    r = view->ops->fetch_int( view, row, col, &ival );
    if( r != ERROR_SUCCESS )
        return r;

1181
    /* check the column value is in range */
1182
    if (ival > tv->num_cols || ival == col)
1183 1184 1185 1186
    {
        ERR("bad column ref (%u) for stream\n", ival);
        return ERROR_FUNCTION_FAILED;
    }
1187

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
    if ( tv->columns[ival - 1].type & MSITYPE_STRING )
    {
        /* now get the column with the name of the stream */
        r = view->ops->fetch_int( view, row, ival, &refcol );
        if ( r != ERROR_SUCCESS )
            return r;

        /* lookup the string value from the string table */
        sval = msi_string_lookup_id( tv->db->strings, refcol );
        if ( !sval )
            return ERROR_INVALID_PARAMETER;
    }
    else
    {
        static const WCHAR fmt[] = { '%','d',0 };
        sprintfW( number, fmt, ival );
        sval = number;
    }
1206

1207
    len = lstrlenW( tv->name ) + 2 + lstrlenW( sval );
1208
    full_name = msi_alloc( len*sizeof(WCHAR) );
1209 1210 1211
    lstrcpyW( full_name, tv->name );
    lstrcatW( full_name, szDot );
    lstrcatW( full_name, sval );
1212 1213 1214 1215

    r = db_get_raw_stream( tv->db, full_name, stm );
    if( r )
        ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1216
    msi_free( full_name );
1217 1218 1219 1220

    return r;
}

1221
static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1222
{
1223
    UINT offset, n, i;
1224
    BYTE **data;
1225 1226 1227 1228 1229 1230 1231

    if( !tv->table )
        return ERROR_INVALID_PARAMETER;

    if( (col==0) || (col>tv->num_cols) )
        return ERROR_INVALID_PARAMETER;

1232 1233 1234
    if( row >= tv->table->row_count + tv->table->nonpersistent_row_count )
        return ERROR_INVALID_PARAMETER;

1235 1236 1237 1238 1239 1240 1241
    if( tv->columns[col-1].offset >= tv->row_size )
    {
        ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
        ERR("%p %p\n", tv, tv->columns );
        return ERROR_FUNCTION_FAILED;
    }

1242 1243 1244
    msi_free( tv->columns[col-1].hash_table );
    tv->columns[col-1].hash_table = NULL;

1245 1246 1247 1248 1249 1250 1251
    if (row >= tv->table->row_count)
    {
        row -= tv->table->row_count;
        data = tv->table->nonpersistent_data;
    }
    else
        data = tv->table->data;
1252

1253
    n = bytes_per_column( tv->db, &tv->columns[col-1] );
1254
    if ( n != 2 && n != 3 && n != 4 )
1255 1256 1257 1258
    {
        ERR("oops! what is %d bytes per column?\n", n );
        return ERROR_FUNCTION_FAILED;
    }
1259

1260 1261 1262
    offset = tv->columns[col-1].offset;
    for ( i = 0; i < n; i++ )
        data[row][offset + i] = (val >> i * 8) & 0xff;
1263

1264 1265 1266
    return ERROR_SUCCESS;
}

1267 1268 1269 1270 1271 1272 1273
static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW *)view;

    if (!tv->table)
        return ERROR_INVALID_PARAMETER;

1274 1275 1276
    if (tv->order)
        row = tv->order->reorder[row];

1277 1278 1279
    return msi_view_get_row(tv->db, view, row, rec);
}

1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    UINT i, val, r = ERROR_SUCCESS;

    if ( !tv->table )
        return ERROR_INVALID_PARAMETER;

    /* test if any of the mask bits are invalid */
    if ( mask >= (1<<tv->num_cols) )
        return ERROR_INVALID_PARAMETER;

    for ( i = 0; i < tv->num_cols; i++ )
    {
1294 1295
        BOOL persistent;

1296 1297 1298 1299
        /* only update the fields specified in the mask */
        if ( !(mask&(1<<i)) )
            continue;

1300 1301
        /* if row >= tv->table->row_count then it is a non-persistent row */
        persistent = tv->table->persistent && (row < tv->table->row_count);
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
        /* FIXME: should we allow updating keys? */

        val = 0;
        if ( !MSI_RecordIsNull( rec, i + 1 ) )
        {
            if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
            {
                val = 1; /* refers to the first key column */
            }
            else if ( tv->columns[i].type & MSITYPE_STRING )
            {
                LPCWSTR sval = MSI_RecordGetString( rec, i + 1 );
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
                UINT ival, x;

                r = msi_string2idW(tv->db->strings, sval, &ival);
                if (r == ERROR_SUCCESS)
                {
                    TABLE_fetch_int(&tv->view, row, i + 1, &x);
                    if (ival == x)
                        continue;
                }

1324 1325
                val = msi_addstringW( tv->db->strings, 0, sval, -1, 1,
                                      persistent ? StringPersistent : StringNonPersistent );
1326
            }
1327
            else if ( 2 == bytes_per_column( tv->db, &tv->columns[ i ] ) )
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
            {
                val = 0x8000 + MSI_RecordGetInteger( rec, i + 1 );
                if ( val & 0xffff0000 )
                {
                    ERR("field %u value %d out of range\n", i+1, val - 0x8000 );
                    return ERROR_FUNCTION_FAILED;
                }
            }
            else
            {
                INT ival = MSI_RecordGetInteger( rec, i + 1 );
                val = ival ^ 0x80000000;
            }
        }

        r = TABLE_set_int( tv, row, i+1, val );
        if ( r != ERROR_SUCCESS )
            break;
    }
    return r;
}

1350
static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1351 1352
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1353
    BYTE **p, *row;
1354
    UINT sz;
1355
    BYTE ***data_ptr;
1356
    UINT *row_count;
1357

1358
    TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1359 1360 1361 1362

    if( !tv->table )
        return ERROR_INVALID_PARAMETER;

1363
    row = msi_alloc_zero( tv->row_size );
1364 1365 1366
    if( !row )
        return ERROR_NOT_ENOUGH_MEMORY;

1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
    if( temporary )
    {
        row_count = &tv->table->nonpersistent_row_count;
        data_ptr = &tv->table->nonpersistent_data;
        *num = tv->table->row_count + tv->table->nonpersistent_row_count;
    }
    else
    {
        row_count = &tv->table->row_count;
        data_ptr = &tv->table->data;
        *num = tv->table->row_count;
    }

1380
    sz = (*row_count + 1) * sizeof (BYTE*);
1381 1382
    if( *data_ptr )
        p = msi_realloc( *data_ptr, sz );
1383
    else
1384
        p = msi_alloc( sz );
1385
    if( !p )
1386
    {
1387
        msi_free( row );
1388
        return ERROR_NOT_ENOUGH_MEMORY;
1389
    }
1390

1391 1392 1393
    *data_ptr = p;
    (*data_ptr)[*row_count] = row;
    (*row_count)++;
1394 1395 1396 1397

    return ERROR_SUCCESS;
}

1398
static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1399 1400 1401
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;

1402
    TRACE("%p %p\n", tv, record);
1403

1404
    TRACE("There are %d columns\n", tv->num_cols );
1405

1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    return ERROR_SUCCESS;
}

static UINT TABLE_close( struct tagMSIVIEW *view )
{
    TRACE("%p\n", view );
    
    return ERROR_SUCCESS;
}

static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;

    TRACE("%p %p %p\n", view, rows, cols );

    if( cols )
        *cols = tv->num_cols;
    if( rows )
    {
        if( !tv->table )
            return ERROR_INVALID_PARAMETER;
1428
        *rows = tv->table->row_count + tv->table->nonpersistent_row_count;
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
    }

    return ERROR_SUCCESS;
}

static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
                UINT n, LPWSTR *name, UINT *type )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;

    TRACE("%p %d %p %p\n", tv, n, name, type );

    if( ( n == 0 ) || ( n > tv->num_cols ) )
        return ERROR_INVALID_PARAMETER;

    if( name )
    {
        *name = strdupW( tv->columns[n-1].colname );
        if( !*name )
            return ERROR_FUNCTION_FAILED;
    }
    if( type )
        *type = tv->columns[n-1].type;

    return ERROR_SUCCESS;
}

1456
static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row );
1457 1458 1459

static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec )
{
1460
    UINT r, row, i;
1461

1462 1463 1464 1465 1466 1467
    /* check there's no null values where they're not allowed */
    for( i = 0; i < tv->num_cols; i++ )
    {
        if ( tv->columns[i].type & MSITYPE_NULLABLE )
            continue;

1468 1469 1470
        if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
            TRACE("skipping binary column\n");
        else if ( tv->columns[i].type & MSITYPE_STRING )
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
        {
            LPCWSTR str;

            str = MSI_RecordGetString( rec, i+1 );
            if (str == NULL || str[0] == 0)
                return ERROR_INVALID_DATA;
        }
        else
        {
            UINT n;

            n = MSI_RecordGetInteger( rec, i+1 );
            if (n == MSI_NULL_INTEGER)
                return ERROR_INVALID_DATA;
        }
    }

    /* check there's no duplicate keys */
1489
    r = msi_table_find_row( tv, rec, &row );
1490
    if (r == ERROR_SUCCESS)
1491
        return ERROR_FUNCTION_FAILED;
1492 1493

    return ERROR_SUCCESS;
1494 1495
}

1496
static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, BOOL temporary )
1497 1498 1499 1500
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    UINT r, row = -1;

1501
    TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1502

1503 1504 1505 1506 1507
    /* check that the key is unique - can we find a matching row? */
    r = table_validate_new( tv, rec );
    if( r != ERROR_SUCCESS )
        return ERROR_FUNCTION_FAILED;

1508
    r = table_create_new_row( view, &row, temporary );
1509 1510 1511 1512
    TRACE("insert_row returned %08x\n", r);
    if( r != ERROR_SUCCESS )
        return r;

1513
    return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1514 1515
}

1516 1517 1518
static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1519
    UINT r, num_rows, num_cols, i;
1520
    BYTE **data;
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533

    TRACE("%p %d\n", tv, row);

    if ( !tv->table )
        return ERROR_INVALID_PARAMETER;

    r = TABLE_get_dimensions( view, &num_rows, &num_cols );
    if ( r != ERROR_SUCCESS )
        return r;

    if ( row >= num_rows )
        return ERROR_FUNCTION_FAILED;

1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
    if ( row < tv->table->row_count )
    {
        num_rows = tv->table->row_count;
        tv->table->row_count--;
        data = tv->table->data;
    }
    else
    {
        num_rows = tv->table->nonpersistent_row_count;
        row -= tv->table->row_count;
        tv->table->nonpersistent_row_count--;
        data = tv->table->nonpersistent_data;
    }
1547

1548 1549 1550 1551 1552 1553 1554
    /* reset the hash tables */
    for (i = 0; i < tv->num_cols; i++)
    {
        msi_free( tv->columns[i].hash_table );
        tv->columns[i].hash_table = NULL;
    }

1555 1556 1557
    if ( row == num_rows - 1 )
        return ERROR_SUCCESS;

1558
    for (i = row + 1; i < num_rows; i++)
1559
        memcpy(data[i - 1], data[i], tv->row_size);
1560

1561 1562 1563
    return ERROR_SUCCESS;
}

1564
static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1565 1566
{
    MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1567
    UINT r, new_row;
1568 1569 1570 1571 1572 1573 1574 1575

    /* FIXME: MsiViewFetch should set rec index 0 to some ID that
     * sets the fetched record apart from other records
     */

    if (!tv->table)
        return ERROR_INVALID_PARAMETER;

1576
    r = msi_table_find_row(tv, rec, &new_row);
1577
    if (r != ERROR_SUCCESS)
1578 1579
    {
        ERR("can't find row to modify\n");
1580
        return ERROR_FUNCTION_FAILED;
1581
    }
1582 1583

    /* the row cannot be changed */
1584
    if (row != new_row + 1)
1585 1586
        return ERROR_FUNCTION_FAILED;

1587
    return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1588 1589
}

1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
    UINT row, r;

    r = msi_table_find_row(tv, rec, &row);
    if (r != ERROR_SUCCESS)
        return r;

    return TABLE_delete_row(view, row);
}

1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
{
    MSIRECORD *curr;
    UINT r, i, count;

    r = TABLE_get_row(view, row - 1, &curr);
    if (r != ERROR_SUCCESS)
        return r;

    count = MSI_RecordGetFieldCount(rec);
    for (i = 0; i < count; i++)
        MSI_RecordCopyField(curr, i + 1, rec, i + 1);

    msiobj_release(&curr->hdr);
    return ERROR_SUCCESS;
}

1619
static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1620
                          MSIRECORD *rec, UINT row)
1621
{
1622 1623 1624 1625 1626 1627 1628
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    UINT r;

    TRACE("%p %d %p\n", view, eModifyMode, rec );

    switch (eModifyMode)
    {
1629 1630 1631
    case MSIMODIFY_DELETE:
        r = modify_delete_row( view, rec );
        break;
1632 1633 1634 1635
    case MSIMODIFY_VALIDATE_NEW:
        r = table_validate_new( tv, rec );
        break;

1636 1637 1638 1639 1640 1641 1642
    case MSIMODIFY_INSERT:
        r = table_validate_new( tv, rec );
        if (r != ERROR_SUCCESS)
            break;
        r = TABLE_insert_row( view, rec, FALSE );
        break;

1643 1644 1645 1646
    case MSIMODIFY_INSERT_TEMPORARY:
        r = table_validate_new( tv, rec );
        if (r != ERROR_SUCCESS)
            break;
1647
        r = TABLE_insert_row( view, rec, TRUE );
1648 1649
        break;

1650 1651 1652 1653
    case MSIMODIFY_REFRESH:
        r = msi_refresh_record( view, rec, row );
        break;

1654
    case MSIMODIFY_UPDATE:
1655
        r = msi_table_update( view, rec, row );
1656 1657
        break;

1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
    case MSIMODIFY_ASSIGN:
    case MSIMODIFY_REPLACE:
    case MSIMODIFY_MERGE:
    case MSIMODIFY_VALIDATE:
    case MSIMODIFY_VALIDATE_FIELD:
    case MSIMODIFY_VALIDATE_DELETE:
        FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
        r = ERROR_CALL_NOT_IMPLEMENTED;
        break;

    default:
        r = ERROR_INVALID_DATA;
    }

    return r;
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
}

static UINT TABLE_delete( struct tagMSIVIEW *view )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;

    TRACE("%p\n", view );

    tv->table = NULL;
    tv->columns = NULL;

1684 1685 1686 1687 1688 1689 1690
    if (tv->order)
    {
        msi_free( tv->order->reorder );
        msi_free( tv->order );
        tv->order = NULL;
    }

1691
    msi_free( tv );
1692 1693 1694 1695

    return ERROR_SUCCESS;
}

1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
    UINT val, UINT *row, MSIITERHANDLE *handle )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    const MSICOLUMNHASHENTRY *entry;

    TRACE("%p, %d, %u, %p\n", view, col, val, *handle);

    if( !tv->table )
        return ERROR_INVALID_PARAMETER;

    if( (col==0) || (col > tv->num_cols) )
        return ERROR_INVALID_PARAMETER;

    if( !tv->columns[col-1].hash_table )
    {
        UINT i;
1713
        UINT num_rows = tv->table->row_count + tv->table->nonpersistent_row_count;
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
        MSICOLUMNHASHENTRY **hash_table;
        MSICOLUMNHASHENTRY *new_entry;

        if( tv->columns[col-1].offset >= tv->row_size )
        {
            ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
            ERR("%p %p\n", tv, tv->columns );
            return ERROR_FUNCTION_FAILED;
        }

        /* allocate contiguous memory for the table and its entries so we
         * don't have to do an expensive cleanup */
        hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
            num_rows * sizeof(MSICOLUMNHASHENTRY));
        if (!hash_table)
            return ERROR_OUTOFMEMORY;

        memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
        tv->columns[col-1].hash_table = hash_table;

        new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);

        for (i = 0; i < num_rows; i++, new_entry++)
        {
1738 1739 1740
            UINT row_value;

            if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
                continue;

            new_entry->next = NULL;
            new_entry->value = row_value;
            new_entry->row = i;
            if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
            {
                MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
                while (prev_entry->next)
                    prev_entry = prev_entry->next;
                prev_entry->next = new_entry;
            }
            else
                hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
        }
    }

    if( !*handle )
        entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
    else
1761
        entry = (*handle)->next;
1762 1763 1764 1765

    while (entry && entry->value != val)
        entry = entry->next;

1766
    *handle = entry;
1767 1768 1769 1770
    if (!entry)
        return ERROR_NO_MORE_ITEMS;

    *row = entry->row;
1771

1772 1773 1774
    return ERROR_SUCCESS;
}

1775 1776 1777
static UINT TABLE_add_ref(struct tagMSIVIEW *view)
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1778
    UINT i;
1779 1780 1781

    TRACE("%p %d\n", view, tv->table->ref_count);

1782 1783 1784 1785 1786 1787
    for (i = 0; i < tv->table->col_count; i++)
    {
        if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
            InterlockedIncrement(&tv->table->colinfo[i].ref_count);
    }

1788 1789 1790
    return InterlockedIncrement(&tv->table->ref_count);
}

1791 1792 1793
static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1794
    MSIRECORD *rec = NULL;
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
    MSIVIEW *columns = NULL;
    UINT row, r;

    rec = MSI_CreateRecord(2);
    if (!rec)
        return ERROR_OUTOFMEMORY;

    MSI_RecordSetStringW(rec, 1, table);
    MSI_RecordSetInteger(rec, 2, number);

    r = TABLE_CreateView(tv->db, szColumns, &columns);
    if (r != ERROR_SUCCESS)
        return r;

    r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row);
    if (r != ERROR_SUCCESS)
        goto done;

    r = TABLE_delete_row(columns, row);
    if (r != ERROR_SUCCESS)
        goto done;

    msi_update_table_columns(tv->db, table);

done:
    msiobj_release(&rec->hdr);
1821
    if (columns) columns->ops->delete(columns);
1822 1823 1824
    return r;
}

1825 1826 1827 1828
static UINT TABLE_release(struct tagMSIVIEW *view)
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    INT ref = tv->table->ref_count;
1829
    UINT i, r;
1830 1831 1832

    TRACE("%p %d\n", view, ref);

1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
    for (i = 0; i < tv->table->col_count; i++)
    {
        if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
        {
            ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
            if (ref == 0)
            {
                r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
                                        tv->table->colinfo[i].number);
                if (r != ERROR_SUCCESS)
                    break;
            }
        }
    }

1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
    ref = InterlockedDecrement(&tv->table->ref_count);
    if (ref == 0)
    {
        if (!tv->table->row_count)
        {
            list_remove(&tv->table->entry);
            free_table(tv->table);
            TABLE_delete(view);
        }
    }

    return ref;
}
1861

1862 1863
static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
                             LPCWSTR column, UINT type, BOOL hold)
1864 1865
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1866
    MSITABLE *msitable;
1867
    MSIRECORD *rec;
1868
    UINT r, i;
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884

    rec = MSI_CreateRecord(4);
    if (!rec)
        return ERROR_OUTOFMEMORY;

    MSI_RecordSetStringW(rec, 1, table);
    MSI_RecordSetInteger(rec, 2, number);
    MSI_RecordSetStringW(rec, 3, column);
    MSI_RecordSetInteger(rec, 4, type);

    r = TABLE_insert_row(&tv->view, rec, FALSE);
    if (r != ERROR_SUCCESS)
        goto done;

    msi_update_table_columns(tv->db, table);

1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
    if (!hold)
        goto done;

    msitable = find_cached_table(tv->db, table);
    for (i = 0; i < msitable->col_count; i++)
    {
        if (!lstrcmpW(msitable->colinfo[i].colname, column))
        {
            InterlockedIncrement(&msitable->colinfo[i].ref_count);
            break;
        }
    }

1898 1899 1900 1901 1902
done:
    msiobj_release(&rec->hdr);
    return r;
}

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
static UINT order_add_column(struct tagMSIVIEW *view, MSIORDERINFO *order, LPCWSTR name)
{
    UINT n, r, count;

    r = TABLE_get_dimensions(view, NULL, &count);
    if (r != ERROR_SUCCESS)
        return r;

    if (order->num_cols >= count)
        return ERROR_FUNCTION_FAILED;

    r = VIEW_find_column(view, name, &n);
    if (r != ERROR_SUCCESS)
        return r;

    order->cols[order->num_cols] = n;
    TRACE("Ordering by column %s (%d)\n", debugstr_w(name), n);

    order->num_cols++;

    return ERROR_SUCCESS;
}

static UINT order_compare(struct tagMSIVIEW *view, MSIORDERINFO *order,
                          UINT a, UINT b, UINT *swap)
{
    UINT r, i, a_val = 0, b_val = 0;

    *swap = 0;
    for (i = 0; i < order->num_cols; i++)
    {
        r = TABLE_fetch_int(view, a, order->cols[i], &a_val);
        if (r != ERROR_SUCCESS)
            return r;

        r = TABLE_fetch_int(view, b, order->cols[i], &b_val);
        if (r != ERROR_SUCCESS)
            return r;

        if (a_val != b_val)
        {
            if (a_val > b_val)
                *swap = 1;
            break;
        }
    }

    return ERROR_SUCCESS;
}

static UINT order_mergesort(struct tagMSIVIEW *view, MSIORDERINFO *order,
                            UINT left, UINT right)
{
    UINT r, i, j, temp;
    UINT swap = 0, center = (left + right) / 2;
    UINT *array = order->reorder;

    if (left == right)
        return ERROR_SUCCESS;

    /* sort the left half */
    r = order_mergesort(view, order, left, center);
    if (r != ERROR_SUCCESS)
        return r;

    /* sort the right half */
    r = order_mergesort(view, order, center + 1, right);
    if (r != ERROR_SUCCESS)
        return r;

    for (i = left, j = center + 1; (i <= center) && (j <= right); i++)
    {
        r = order_compare(view, order, array[i], array[j], &swap);
        if (r != ERROR_SUCCESS)
            return r;

        if (swap)
        {
            temp = array[j];
            memmove(&array[i + 1], &array[i], (j - i) * sizeof(UINT));
            array[i] = temp;
            j++;
            center++;
        }
    }

    return ERROR_SUCCESS;
}

static UINT order_verify(struct tagMSIVIEW *view, MSIORDERINFO *order, UINT num_rows)
{
    UINT i, swap, r;

    for (i = 1; i < num_rows; i++)
    {
        r = order_compare(view, order, order->reorder[i - 1],
                          order->reorder[i], &swap);
        if (r != ERROR_SUCCESS)
            return r;

        if (!swap)
            continue;

        ERR("Bad order! %d\n", i);
        return ERROR_FUNCTION_FAILED;
    }

    return ERROR_SUCCESS;
}

static UINT TABLE_sort(struct tagMSIVIEW *view, column_info *columns)
{
    MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
    MSIORDERINFO *order;
    column_info *ptr;
    UINT r, i;
    UINT rows, cols;

    TRACE("sorting table %s\n", debugstr_w(tv->name));

    r = TABLE_get_dimensions(view, &rows, &cols);
    if (r != ERROR_SUCCESS)
        return r;

2027 2028 2029
    if (rows == 0)
        return ERROR_SUCCESS;

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
    order = msi_alloc_zero(sizeof(MSIORDERINFO) + sizeof(UINT) * cols);
    if (!order)
        return ERROR_OUTOFMEMORY;

    for (ptr = columns; ptr; ptr = ptr->next)
        order_add_column(view, order, ptr->column);

    order->reorder = msi_alloc(rows * sizeof(UINT));
    if (!order->reorder)
        return ERROR_OUTOFMEMORY;

    for (i = 0; i < rows; i++)
        order->reorder[i] = i;

    r = order_mergesort(view, order, 0, rows - 1);
    if (r != ERROR_SUCCESS)
        return r;

    r = order_verify(view, order, rows);
    if (r != ERROR_SUCCESS)
        return r;

    tv->order = order;

    return ERROR_SUCCESS;
}

2057 2058 2059 2060 2061
static UINT TABLE_drop(struct tagMSIVIEW *view)
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    MSIVIEW *tables = NULL;
    MSIRECORD *rec = NULL;
2062 2063
    UINT r, row;
    INT i;
2064 2065 2066

    TRACE("dropping table %s\n", debugstr_w(tv->name));

2067
    for (i = tv->table->col_count - 1; i >= 0; i--)
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
    {
        r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
                                tv->table->colinfo[i].number);
        if (r != ERROR_SUCCESS)
            return r;
    }

    rec = MSI_CreateRecord(1);
    if (!rec)
        return ERROR_OUTOFMEMORY;

    MSI_RecordSetStringW(rec, 1, tv->name);

    r = TABLE_CreateView(tv->db, szTables, &tables);
    if (r != ERROR_SUCCESS)
        return r;

    r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row);
    if (r != ERROR_SUCCESS)
        goto done;

    r = TABLE_delete_row(tables, row);
    if (r != ERROR_SUCCESS)
        goto done;

    list_remove(&tv->table->entry);
    free_table(tv->table);
    TABLE_delete(view);

done:
    msiobj_release(&rec->hdr);
    tables->ops->delete(tables);

    return r;
}

2104
static const MSIVIEWOPS table_ops =
2105 2106
{
    TABLE_fetch_int,
2107
    TABLE_fetch_stream,
2108
    TABLE_get_row,
2109
    TABLE_set_row,
2110
    TABLE_insert_row,
2111
    TABLE_delete_row,
2112 2113 2114 2115 2116
    TABLE_execute,
    TABLE_close,
    TABLE_get_dimensions,
    TABLE_get_column_info,
    TABLE_modify,
2117
    TABLE_delete,
2118 2119 2120
    TABLE_find_matching_rows,
    TABLE_add_ref,
    TABLE_release,
2121
    TABLE_add_column,
2122
    TABLE_remove_column,
2123
    TABLE_sort,
2124
    TABLE_drop,
2125 2126
};

2127
UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2128 2129
{
    MSITABLEVIEW *tv ;
2130
    UINT r, sz;
2131

2132
    static const WCHAR Streams[] = {'_','S','t','r','e','a','m','s',0};
2133
    static const WCHAR Storages[] = {'_','S','t','o','r','a','g','e','s',0};
2134

2135 2136
    TRACE("%p %s %p\n", db, debugstr_w(name), view );

2137 2138
    if ( !lstrcmpW( name, Streams ) )
        return STREAMS_CreateView( db, view );
2139 2140
    else if ( !lstrcmpW( name, Storages ) )
        return STORAGES_CreateView( db, view );
2141

2142
    sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
2143
    tv = msi_alloc_zero( sz );
2144 2145 2146
    if( !tv )
        return ERROR_FUNCTION_FAILED;

2147
    r = get_table( db, name, &tv->table );
2148 2149
    if( r != ERROR_SUCCESS )
    {
2150
        msi_free( tv );
2151 2152
        WARN("table not found\n");
        return r;
2153 2154
    }

2155
    TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2156 2157 2158 2159

    /* fill the structure */
    tv->view.ops = &table_ops;
    tv->db = db;
2160 2161
    tv->columns = tv->table->colinfo;
    tv->num_cols = tv->table->col_count;
2162
    tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count );
2163

2164
    TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2165 2166 2167 2168 2169 2170

    *view = (MSIVIEW*) tv;
    lstrcpyW( tv->name, name );

    return ERROR_SUCCESS;
}
2171 2172 2173 2174 2175 2176

UINT MSI_CommitTables( MSIDATABASE *db )
{
    UINT r;
    MSITABLE *table = NULL;

2177 2178
    TRACE("%p\n",db);

2179
    r = msi_save_string_table( db->strings, db->storage );
2180 2181
    if( r != ERROR_SUCCESS )
    {
2182
        WARN("failed to save string table r=%08x\n",r);
2183 2184
        return r;
    }
2185

2186
    LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2187 2188 2189
    {
        r = save_table( db, table );
        if( r != ERROR_SUCCESS )
2190
        {
2191
            WARN("failed to save table %s (r=%08x)\n",
2192
                  debugstr_w(table->name), r);
2193
            return r;
2194
        }
2195 2196 2197 2198 2199 2200 2201
    }

    /* force everything to reload next time */
    free_cached_tables( db );

    return ERROR_SUCCESS;
}
2202

2203 2204
MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
{
2205 2206 2207 2208 2209
    MSITABLE *t;
    UINT r;

    TRACE("%p %s\n", db, debugstr_w(table));

2210 2211 2212
    if (!table)
        return MSICONDITION_ERROR;

2213 2214
    r = get_table( db, table, &t );
    if (r != ERROR_SUCCESS)
2215 2216
        return MSICONDITION_NONE;

2217 2218 2219 2220
    if (t->persistent)
        return MSICONDITION_TRUE;
    else
        return MSICONDITION_FALSE;
2221 2222
}

2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
{
    UINT ret = 0, i;

    for (i = 0; i < bytes; i++)
        ret += (data[col + i] << i * 8);

    return ret;
}

2233
static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2234
                                            const BYTE *rawdata, UINT bytes_per_strref )
2235 2236
{
    UINT i, val, ofs = 0;
2237
    USHORT mask;
2238 2239 2240
    MSICOLUMNINFO *columns = tv->columns;
    MSIRECORD *rec;

2241 2242 2243
    mask = rawdata[0] | (rawdata[1] << 8);
    rawdata += 2;

2244 2245 2246 2247
    rec = MSI_CreateRecord( tv->num_cols );
    if( !rec )
        return rec;

2248
    TRACE("row ->\n");
2249 2250 2251 2252 2253 2254 2255 2256
    for( i=0; i<tv->num_cols; i++ )
    {
        if ( (mask&1) && (i>=(mask>>8)) )
            break;
        /* all keys must be present */
        if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
            continue;

2257 2258
        if( (columns[i].type & MSITYPE_STRING) &&
            ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2259
        {
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
            LPCWSTR sval;

            val = read_raw_int(rawdata, ofs, bytes_per_strref);
            sval = msi_string_lookup_id( st, val );
            MSI_RecordSetStringW( rec, i+1, sval );
            TRACE(" field %d [%s]\n", i+1, debugstr_w(sval));
            ofs += bytes_per_strref;
        }
        else
        {
2270
            UINT n = bytes_per_column( tv->db, &columns[i] );
2271
            switch( n )
2272
            {
2273 2274
            case 2:
                val = read_raw_int(rawdata, ofs, n);
2275 2276
                if (val)
                    MSI_RecordSetInteger( rec, i+1, val^0x8000 );
2277
                TRACE(" field %d [0x%04x]\n", i+1, val );
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
                break;
            case 4:
                val = read_raw_int(rawdata, ofs, n);
                if (val)
                    MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
                TRACE(" field %d [0x%08x]\n", i+1, val );
                break;
            default:
                ERR("oops - unknown column width %d\n", n);
                break;
2288
            }
2289
            ofs += n;
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
        }
    }
    return rec;
}

static void dump_record( MSIRECORD *rec )
{
    UINT i, n;

    n = MSI_RecordGetFieldCount( rec );
    for( i=1; i<=n; i++ )
    {
        LPCWSTR sval = MSI_RecordGetString( rec, i );

        if( MSI_RecordIsNull( rec, i ) )
2305
            TRACE("row -> []\n");
2306
        else if( (sval = MSI_RecordGetString( rec, i )) )
2307
            TRACE("row -> [%s]\n", debugstr_w(sval));
2308
        else
2309
            TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2310 2311 2312
    }
}

2313
static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324
{
    LPCWSTR sval;
    UINT i;

    for( i=0; i<(rawsize/2); i++ )
    {
        sval = msi_string_lookup_id( st, rawdata[i] );
        MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
    }
}

2325
static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
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
{
    LPCWSTR str;
    UINT i, r, *data;

    data = msi_alloc( tv->num_cols *sizeof (UINT) );
    for( i=0; i<tv->num_cols; i++ )
    {
        data[i] = 0;

        if ( ~tv->columns[i].type & MSITYPE_KEY )
            continue;

        /* turn the transform column value into a row value */
        if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
             ! MSITYPE_IS_BINARY(tv->columns[i].type) )
        {
            str = MSI_RecordGetString( rec, i+1 );
            r = msi_string2idW( tv->db->strings, str, &data[i] );

            /* if there's no matching string in the string table,
               these keys can't match any record, so fail now. */
            if( ERROR_SUCCESS != r )
            {
                msi_free( data );
                return NULL;
            }
        }
        else
2354
        {
2355
            data[i] = MSI_RecordGetInteger( rec, i+1 );
2356 2357 2358 2359 2360
            if ((tv->columns[i].type&0xff) == 2)
                data[i] += 0x8000;
            else
                data[i] += 0x80000000;
        }
2361 2362 2363 2364
    }
    return data;
}

2365
static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data )
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
{
    UINT i, r, x, ret = ERROR_FUNCTION_FAILED;

    for( i=0; i<tv->num_cols; i++ )
    {
        if ( ~tv->columns[i].type & MSITYPE_KEY )
            continue;

        /* turn the transform column value into a row value */
        r = TABLE_fetch_int( &tv->view, row, i+1, &x );
        if ( r != ERROR_SUCCESS )
        {
            ERR("TABLE_fetch_int shouldn't fail here\n");
            break;
        }

        /* if this key matches, move to the next column */
        if ( x != data[i] )
        {
            ret = ERROR_FUNCTION_FAILED;
            break;
        }

        ret = ERROR_SUCCESS;
    }

    return ret;
}

static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row )
{
    UINT i, r = ERROR_FUNCTION_FAILED, *data;

    data = msi_record_to_row( tv, rec );
    if( !data )
        return r;
2402
    for( i = 0; i < tv->table->row_count + tv->table->nonpersistent_row_count; i++ )
2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414
    {
        r = msi_row_matches( tv, i, data );
        if( r == ERROR_SUCCESS )
        {
            *row = i;
            break;
        }
    }
    msi_free( data );
    return r;
}

2415 2416 2417 2418 2419 2420
typedef struct
{
    struct list entry;
    LPWSTR name;
} TRANSFORMDATA;

2421
static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2422
                                      string_table *st, TRANSFORMDATA *transform,
2423
                                      UINT bytes_per_strref )
2424
{
2425
    UINT rawsize = 0;
2426
    BYTE *rawdata = NULL;
2427 2428 2429
    MSITABLEVIEW *tv = NULL;
    UINT r, n, sz, i, mask;
    MSIRECORD *rec = NULL;
2430
    UINT colcol = 0;
2431
    WCHAR coltable[32];
2432 2433 2434 2435 2436 2437
    LPWSTR name;

    if (!transform)
        return ERROR_SUCCESS;

    name = transform->name;
2438

2439
    coltable[0] = 0;
2440 2441
    TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );

2442
    /* read the transform data */
2443
    read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2444 2445 2446 2447 2448 2449
    if ( !rawdata )
    {
        TRACE("table %s empty\n", debugstr_w(name) );
        return ERROR_INVALID_TABLE;
    }

2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463
    /* create a table view */
    r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
    if( r != ERROR_SUCCESS )
        goto err;

    r = tv->view.ops->execute( &tv->view, NULL );
    if( r != ERROR_SUCCESS )
        goto err;

    TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
          debugstr_w(name), tv->num_cols, tv->row_size, rawsize );

    /* interpret the data */
    r = ERROR_SUCCESS;
2464
    for( n=0; n < rawsize;  )
2465
    {
2466
        mask = rawdata[n] | (rawdata[n+1] << 8);
2467 2468 2469 2470 2471 2472 2473

        if (mask&1)
        {
            /*
             * if the low bit is set, columns are continuous and
             * the number of columns is specified in the high byte
             */
2474 2475 2476 2477 2478 2479 2480
            sz = 2;
            for( i=0; i<tv->num_cols; i++ )
            {
                if( (tv->columns[i].type & MSITYPE_STRING) &&
                    ! MSITYPE_IS_BINARY(tv->columns[i].type) )
                    sz += bytes_per_strref;
                else
2481
                    sz += bytes_per_column( tv->db, &tv->columns[i] );
2482
            }
2483 2484 2485 2486
        }
        else
        {
            /*
2487
             * If the low bit is not set, mask is a bitmask.
2488 2489 2490
             * Excepting for key fields, which are always present,
             *  each bit indicates that a field is present in the transform record.
             *
2491
             * mask == 0 is a special case ... only the keys will be present
2492 2493 2494 2495 2496 2497
             * and it means that this row should be deleted.
             */
            sz = 2;
            for( i=0; i<tv->num_cols; i++ )
            {
                if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
2498 2499 2500 2501 2502
                {
                    if( (tv->columns[i].type & MSITYPE_STRING) &&
                        ! MSITYPE_IS_BINARY(tv->columns[i].type) )
                        sz += bytes_per_strref;
                    else
2503
                        sz += bytes_per_column( tv->db, &tv->columns[i] );
2504
                }
2505 2506 2507 2508 2509 2510 2511
            }
        }

        /* check we didn't run of the end of the table */
        if ( (n+sz) > rawsize )
        {
            ERR("borked.\n");
2512
            dump_table( st, (USHORT *)rawdata, rawsize );
2513 2514 2515
            break;
        }

2516
        rec = msi_get_transform_record( tv, st, &rawdata[n], bytes_per_strref );
2517 2518
        if (rec)
        {
2519
            if ( mask & 1 )
2520
            {
2521 2522 2523 2524
                WCHAR table[32];
                DWORD sz = 32;
                UINT number = MSI_NULL_INTEGER;

2525
                TRACE("inserting record\n");
2526 2527 2528

                if (!lstrcmpW(name, szColumns))
                {
2529
                    MSI_RecordGetStringW( rec, 1, table, &sz );
2530
                    number = MSI_RecordGetInteger( rec, 2 );
2531

2532 2533 2534 2535 2536
                    /*
                     * Native msi seems writes nul into the Number (2nd) column of
                     * the _Columns table, only when the columns are from a new table
                     */
                    if ( number == MSI_NULL_INTEGER )
2537
                    {
2538 2539 2540 2541 2542 2543 2544 2545 2546
                        /* reset the column number on a new table */
                        if ( lstrcmpW(coltable, table) )
                        {
                            colcol = 0;
                            lstrcpyW( coltable, table );
                        }

                        /* fix nul column numbers */
                        MSI_RecordSetInteger( rec, 2, ++colcol );
2547
                    }
2548 2549
                }

2550
                r = TABLE_insert_row( &tv->view, rec, FALSE );
2551 2552
                if (r != ERROR_SUCCESS)
                    ERR("insert row failed\n");
2553 2554 2555

                if ( number != MSI_NULL_INTEGER && !lstrcmpW(name, szColumns) )
                    msi_update_table_columns( db, table );
2556 2557 2558
            }
            else
            {
2559 2560 2561 2562 2563 2564 2565
                UINT row = 0;

                r = msi_table_find_row( tv, rec, &row );
                if (r != ERROR_SUCCESS)
                    ERR("no matching row to transform\n");
                else if ( mask )
                {
2566
                    TRACE("modifying row [%d]:\n", row);
2567
                    TABLE_set_row( &tv->view, row, rec, mask );
2568 2569 2570
                }
                else
                {
2571
                    TRACE("deleting row [%d]:\n", row);
2572
                    TABLE_delete_row( &tv->view, row );
2573
                }
2574
            }
2575
            if( TRACE_ON(msidb) ) dump_record( rec );
2576 2577 2578
            msiobj_release( &rec->hdr );
        }

2579
        n += sz;
2580 2581 2582 2583 2584 2585 2586 2587
    }

err:
    /* no need to free the table, it's associated with the database */
    msi_free( rawdata );
    if( tv )
        tv->view.ops->delete( &tv->view );

2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
    return ERROR_SUCCESS;
}

/*
 * msi_table_apply_transform
 *
 * Enumerate the table transforms in a transform storage and apply each one.
 */
UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
{
2598
    struct list transforms;
2599
    IEnumSTATSTG *stgenum = NULL;
2600 2601
    TRANSFORMDATA *transform;
    TRANSFORMDATA *tables = NULL, *columns = NULL;
2602 2603 2604 2605
    HRESULT r;
    STATSTG stat;
    string_table *strings;
    UINT ret = ERROR_FUNCTION_FAILED;
2606
    UINT bytes_per_strref;
2607

2608 2609
    TRACE("%p %p\n", db, stg );

2610
    strings = msi_load_string_table( stg, &bytes_per_strref );
2611 2612 2613 2614 2615 2616 2617
    if( !strings )
        goto end;

    r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
    if( FAILED( r ) )
        goto end;

2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630
    list_init(&transforms);

    while ( TRUE )
    {
        MSITABLEVIEW *tv = NULL;
        WCHAR name[0x40];
        ULONG count = 0;

        r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
        if ( FAILED( r ) || !count )
            break;

        decode_streamname( stat.pwcsName, name );
2631
        CoTaskMemFree( stat.pwcsName );
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
        if ( name[0] != 0x4840 )
            continue;

        if ( !lstrcmpW( name+1, szStringPool ) ||
             !lstrcmpW( name+1, szStringData ) )
            continue;

        transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
        if ( !transform )
            break;

        list_add_tail( &transforms, &transform->entry );

        transform->name = strdupW( name + 1 );

        if ( !lstrcmpW( transform->name, szTables ) )
            tables = transform;
        else if (!lstrcmpW( transform->name, szColumns ) )
            columns = transform;

        TRACE("transform contains stream %s\n", debugstr_w(name));

        /* load the table */
        r = TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv );
        if( r != ERROR_SUCCESS )
            continue;

        r = tv->view.ops->execute( &tv->view, NULL );
        if( r != ERROR_SUCCESS )
        {
            tv->view.ops->delete( &tv->view );
            continue;
        }

        tv->view.ops->delete( &tv->view );
    }

2669
    /*
Mike McCormack's avatar
Mike McCormack committed
2670
     * Apply _Tables and _Columns transforms first so that
2671 2672
     * the table metadata is correct, and empty tables exist.
     */
2673
    ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2674 2675 2676
    if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
        goto end;

2677
    ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2678 2679 2680
    if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
        goto end;

2681 2682
    ret = ERROR_SUCCESS;

2683
    while ( !list_empty( &transforms ) )
2684
    {
2685
        transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2686

2687 2688 2689 2690 2691 2692
        if ( lstrcmpW( transform->name, szColumns ) &&
             lstrcmpW( transform->name, szTables ) &&
             ret == ERROR_SUCCESS )
        {
            ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
        }
2693

2694 2695 2696
        list_remove( &transform->entry );
        msi_free( transform->name );
        msi_free( transform );
2697 2698
    }

2699
    if ( ret == ERROR_SUCCESS )
2700
        append_storage_to_db( db, stg );
2701

2702 2703 2704 2705 2706 2707 2708 2709
end:
    if ( stgenum )
        IEnumSTATSTG_Release( stgenum );
    if ( strings )
        msi_destroy_stringtable( strings );

    return ret;
}
2710

2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
{
    MSITRANSFORM *t;

    t = msi_alloc( sizeof *t );
    t->stg = stg;
    IStorage_AddRef( stg );
    list_add_tail( &db->transforms, &t->entry );
}

2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
void msi_free_transforms( MSIDATABASE *db )
{
    while( !list_empty( &db->transforms ) )
    {
        MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
                                      MSITRANSFORM, entry );
        list_remove( &t->entry );
        IStorage_Release( t->stg );
        msi_free( t );
    }
}