table.c 74.6 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
    BOOL   temporary;
63
    MSICOLUMNHASHENTRY **hash_table;
64 65
} MSICOLUMNINFO;

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

73 74
struct tagMSITABLE
{
75
    BYTE **data;
76
    BOOL *data_persistent;
77
    UINT row_count;
78
    struct list entry;
79 80
    MSICOLUMNINFO *colinfo;
    UINT col_count;
81
    MSICONDITION 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, 0, NULL },
    { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2,     2, 0, 0, NULL },
    { szColumns, 3, szName,   MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, 0, NULL },
    { szColumns, 4, szType,   MSITYPE_VALID | 2,                   6, 0, 0, NULL },
109
};
110 111

static const MSICOLUMNINFO _Tables_cols[1] = {
112
    { szTables,  1, szName,   MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 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
    msi_free( table->data_persistent );
479 480
    msi_free_colinfo( table->colinfo, table->col_count );
    msi_free( table->colinfo );
481
    msi_free( table );
482 483
}

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

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

499
    TRACE("%s\n",debugstr_w(t->name));
500

501
    row_size = msi_table_get_row_size( db, t->colinfo, t->col_count );
502 503

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

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

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

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

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

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

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

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

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

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

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

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

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

Mike McCormack's avatar
Mike McCormack committed
576
    return NULL;
577 578
}

579 580
static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
{
581
    UINT r, column_count = 0;
582 583 584 585 586 587 588 589
    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;

590 591
    *pcount = column_count;

592 593 594 595 596 597
    /* 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) );

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

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

    *pcols = columns;

    return r;
}

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

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

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

635
    table->ref_count = 1;
636 637
    table->row_count = 0;
    table->data = NULL;
638
    table->data_persistent = NULL;
639 640
    table->colinfo = NULL;
    table->col_count = 0;
641
    table->persistent = persistent;
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
    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;
661
        table->colinfo[ i ].ref_count = 0;
662
        table->colinfo[ i ].hash_table = NULL;
663
        table->colinfo[ i ].temporary = col->temporary;
664
    }
665
    table_calc_column_offsets( db, table->colinfo, table->col_count);
666

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

    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;

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

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

    msiobj_release( &rec->hdr );
697
    rec = NULL;
698

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

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

711 712
        rec = MSI_CreateRecord( 4 );
        if( !rec )
713 714
            goto err;

715
        r = MSI_RecordSetStringW( rec, 1, name );
716 717 718
        if( r )
            goto err;

719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
        /*
         * 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;

738
            r = tv->ops->insert_row( tv, rec, -1, FALSE );
739 740 741 742 743 744 745
            if( r )
                goto err;

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

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)
756 757 758 759 760 761 762
    {
        list_add_head( &db->tables, &table->entry );
        *table_ret = table;
    }
    else
        free_table( table );

763 764 765
    return r;
}

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

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

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

784 785
    table->row_count = 0;
    table->data = NULL;
786
    table->data_persistent = NULL;
787 788
    table->colinfo = NULL;
    table->col_count = 0;
789
    table->persistent = MSICONDITION_TRUE;
790 791
    lstrcpyW( table->name, name );

792 793 794
    if ( !lstrcmpW(name, szTables) || !lstrcmpW(name, szColumns) )
        table->persistent = MSICONDITION_NONE;

795 796
    r = table_get_column_info( db, name, &table->colinfo, &table->col_count);
    if (r != ERROR_SUCCESS)
797
    {
798 799
        free_table ( table );
        return r;
800 801
    }

802
    r = read_table_from_storage( db, table, db->storage );
803 804 805 806 807 808 809 810 811
    if( r != ERROR_SUCCESS )
    {
        free_table( table );
        return r;
    }

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

814
static UINT save_table( MSIDATABASE *db, const MSITABLE *t )
815
{
816
    BYTE *rawdata = NULL, *p;
817
    UINT rawsize, r, i, j, row_size;
818

819
    /* Nothing to do for non-persistent tables */
820
    if( t->persistent == MSICONDITION_FALSE )
821 822
        return ERROR_SUCCESS;

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

825
    row_size = msi_table_get_row_size( db, t->colinfo, t->col_count );
826 827

    rawsize = t->row_count * row_size;
828
    rawdata = msi_alloc_zero( rawsize );
829
    if( !rawdata )
830 831 832 833
    {
        r = ERROR_NOT_ENOUGH_MEMORY;
        goto err;
    }
834

835
    rawsize = 0;
836
    p = rawdata;
837
    for( i=0; i<t->col_count; i++ )
838 839 840
    {
        for( j=0; j<t->row_count; j++ )
        {
841
            UINT offset = t->colinfo[i].offset;
842

843 844 845 846
            if (!t->data_persistent[j]) continue;
            if (i == 0)
                rawsize += row_size;

847 848
            *p++ = t->data[j][offset];
            *p++ = t->data[j][offset + 1];
849
            if( 4 == bytes_per_column( db, &t->colinfo[i] ) )
850 851 852 853
            {
                *p++ = t->data[j][offset + 2];
                *p++ = t->data[j][offset + 3];
            }
854 855 856 857
        }
    }

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

860
err:
861
    msi_free( rawdata );
862 863 864 865

    return r;
}

866 867
static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo,
                                       DWORD count )
868 869 870 871 872 873 874 875
{
    DWORD i;

    for( i=0; colinfo && (i<count); i++ )
    {
         assert( (i+1) == colinfo[ i ].number );
         if (i)
             colinfo[i].offset = colinfo[ i - 1 ].offset
876
                               + bytes_per_column( db, &colinfo[ i - 1 ] );
877 878 879 880 881 882 883 884
         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);
    }
}

885 886
static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name,
                                     MSICOLUMNINFO *colinfo, UINT *sz)
887
{
888 889 890 891
    const MSICOLUMNINFO *p;
    DWORD i, n;

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

893
    if (!lstrcmpW( name, szTables ))
894
    {
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
        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) )
910
        {
911
            colinfo[i] = p[i];
912 913
            colinfo[i].tablename = strdupW( p[i].tablename );
            colinfo[i].colname = strdupW( p[i].colname );
914
        }
915
        if( colinfo && (i >= *sz) )
916 917
            break;
    }
918
    table_calc_column_offsets( db, colinfo, n );
919 920 921 922
    *sz = n;
    return ERROR_SUCCESS;
}

923 924 925 926 927 928
static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
{
    UINT i;

    for( i=0; i<count; i++ )
    {
929 930
        msi_free( colinfo[i].tablename );
        msi_free( colinfo[i].colname );
931
        msi_free( colinfo[i].hash_table );
932 933 934
    }
}

935
static LPWSTR msi_makestring( const MSIDATABASE *db, UINT stringid)
936
{
937
    return strdupW(msi_string_lookup_id( db->strings, stringid ));
938 939
}

940
static UINT read_table_int(BYTE *const *data, UINT row, UINT col, UINT bytes)
941 942 943
{
    UINT ret = 0, i;

944 945
    for (i = 0; i < bytes; i++)
        ret += (data[row][col + i] << i * 8);
946 947 948 949

    return ret;
}

950
static UINT get_tablecolumns( MSIDATABASE *db,
951 952 953 954 955
       LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
{
    UINT r, i, n=0, table_id, count, maxcount = *sz;
    MSITABLE *table = NULL;

956
    TRACE("%s\n", debugstr_w(szTableName));
957

958
    /* first check if there is a default table with that name */
959
    r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
960 961 962
    if( ( r == ERROR_SUCCESS ) && *sz )
        return r;

963 964
    r = get_table( db, szColumns, &table );
    if( r != ERROR_SUCCESS )
965
    {
966
        ERR("couldn't load _Columns table\n");
Mike McCormack's avatar
Mike McCormack committed
967
        return ERROR_FUNCTION_FAILED;
968 969 970
    }

    /* convert table and column names to IDs from the string table */
971
    r = msi_string2idW( db->strings, szTableName, &table_id );
972 973
    if( r != ERROR_SUCCESS )
    {
974
        WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
975 976 977
        return r;
    }

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

980 981
    /* Note: _Columns table doesn't have non-persistent data */

982 983
    /* if maxcount is non-zero, assume it's exactly right for this table */
    memset( colinfo, 0, maxcount*sizeof(*colinfo) );
984
    count = table->row_count;
985 986
    for( i=0; i<count; i++ )
    {
987
        if( read_table_int(table->data, i, 0, db->bytes_per_strref) != table_id )
988 989 990
            continue;
        if( colinfo )
        {
991 992
            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);
993 994 995 996 997 998 999 1000 1001 1002

            /* 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)
1003
            {
1004 1005
                ERR("duplicate column %d\n", col);
                continue;
1006
            }
1007 1008 1009 1010

            colinfo[ col - 1 ].tablename = msi_makestring( db, table_id );
            colinfo[ col - 1 ].number = col;
            colinfo[ col - 1 ].colname = msi_makestring( db, id );
1011 1012 1013
            colinfo[ col - 1 ].type = read_table_int(table->data, i,
                                                     table->colinfo[3].offset,
                                                     sizeof(USHORT)) - (1<<15);
1014
            colinfo[ col - 1 ].offset = 0;
1015
            colinfo[ col - 1 ].ref_count = 0;
1016
            colinfo[ col - 1 ].hash_table = NULL;
1017 1018
        }
        n++;
1019 1020 1021 1022
    }

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

1023
    if (colinfo && n != maxcount)
1024 1025 1026 1027 1028 1029
    {
        ERR("missing column in table %s\n", debugstr_w(szTableName));
        msi_free_colinfo(colinfo, maxcount );
        return ERROR_FUNCTION_FAILED;
    }

1030
    table_calc_column_offsets( db, colinfo, n );
1031 1032 1033 1034 1035
    *sz = n;

    return ERROR_SUCCESS;
}

1036 1037 1038
static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
{
    MSITABLE *table;
1039
    UINT size, offset, old_count;
1040
    UINT n;
1041 1042

    table = find_cached_table( db, name );
1043
    old_count = table->col_count;
1044
    msi_free( table->colinfo );
Hans Leidekker's avatar
Hans Leidekker committed
1045
    table->colinfo = NULL;
1046

Hans Leidekker's avatar
Hans Leidekker committed
1047
    table_get_column_info( db, name, &table->colinfo, &table->col_count );
1048 1049 1050
    if (!table->col_count)
        return;

1051
    size = msi_table_get_row_size( db, table->colinfo, table->col_count );
1052 1053 1054 1055 1056
    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 );
1057 1058
        if (old_count < table->col_count)
            memset( &table->data[n][offset], 0, size - offset );
1059 1060 1061
    }
}

1062
/* try to find the table name in the _Tables table */
1063
BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
1064 1065 1066 1067
{
    UINT r, table_id = 0, i, count;
    MSITABLE *table = NULL;

1068 1069 1070 1071 1072
    static const WCHAR szStreams[] = {'_','S','t','r','e','a','m','s',0};
    static const WCHAR szStorages[] = {'_','S','t','o','r','a','g','e','s',0};

    if( !lstrcmpW( name, szTables ) || !lstrcmpW( name, szColumns ) ||
        !lstrcmpW( name, szStreams ) || !lstrcmpW( name, szStorages ) )
1073 1074
        return TRUE;

1075
    r = msi_string2idW( db->strings, name, &table_id );
1076 1077
    if( r != ERROR_SUCCESS )
    {
1078
        TRACE("Couldn't find id for %s\n", debugstr_w(name));
1079 1080 1081
        return FALSE;
    }

1082 1083
    r = get_table( db, szTables, &table );
    if( r != ERROR_SUCCESS )
1084
    {
1085
        ERR("table %s not available\n", debugstr_w(szTables));
1086 1087 1088
        return FALSE;
    }

1089
    count = table->row_count;
1090
    for( i=0; i<count; i++ )
1091
        if( table->data[ i ][ 0 ] == table_id )
1092
            return TRUE;
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104

    return FALSE;
}

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

typedef struct tagMSITABLEVIEW
{
    MSIVIEW        view;
    MSIDATABASE   *db;
    MSITABLE      *table;
    MSICOLUMNINFO *columns;
1105
    MSIORDERINFO  *order;
1106 1107 1108 1109 1110 1111 1112 1113
    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;
1114
    UINT offset, n;
1115 1116 1117 1118 1119 1120 1121 1122

    if( !tv->table )
        return ERROR_INVALID_PARAMETER;

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

    /* how many rows are there ? */
1123
    if( row >= tv->table->row_count )
1124 1125 1126 1127 1128 1129 1130 1131 1132
        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;
    }

1133 1134 1135
    if (tv->order)
        row = tv->order->reorder[row];

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

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

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

    return ERROR_SUCCESS;
}

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
static UINT msi_stream_name( const MSITABLEVIEW *tv, UINT row, LPWSTR *pstname )
{
    LPWSTR p, stname = NULL;
    UINT i, r, type, ival;
    DWORD len;
    LPCWSTR sval;
    MSIVIEW *view = (MSIVIEW *) tv;

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

    len = lstrlenW( tv->name ) + 1;
    stname = msi_alloc( len*sizeof(WCHAR) );
    if ( !stname )
    {
       r = ERROR_OUTOFMEMORY;
       goto err;
    }

    lstrcpyW( stname, tv->name );

    for ( i = 0; i < tv->num_cols; i++ )
    {
        type = tv->columns[i].type;
        if ( type & MSITYPE_KEY )
        {
            static const WCHAR szDot[] = { '.', 0 };

            r = TABLE_fetch_int( view, row, i+1, &ival );
            if ( r != ERROR_SUCCESS )
                goto err;

            if ( tv->columns[i].type & MSITYPE_STRING )
            {
                sval = msi_string_lookup_id( tv->db->strings, ival );
                if ( !sval )
                {
                    r = ERROR_INVALID_PARAMETER;
                    goto err;
                }
            }
            else
            {
                static const WCHAR fmt[] = { '%','d',0 };
                WCHAR number[0x20];
                UINT n = bytes_per_column( tv->db, &tv->columns[i] );

                switch( n )
                {
                case 2:
                    sprintfW( number, fmt, ival^0x8000 );
                    break;
                case 4:
                    sprintfW( number, fmt, ival^0x80000000 );
                    break;
                default:
                    ERR( "oops - unknown column width %d\n", n );
                    r = ERROR_FUNCTION_FAILED;
                    goto err;
                }
                sval = number;
            }

            len += lstrlenW( szDot ) + lstrlenW( sval );
            p = msi_realloc ( stname, len*sizeof(WCHAR) );
            if ( !p )
            {
                r = ERROR_OUTOFMEMORY;
                goto err;
            }
            stname = p;

            lstrcatW( stname, szDot );
            lstrcatW( stname, sval );
        }
        else
           continue;
    }

    *pstname = stname;
    return ERROR_SUCCESS;

err:
    msi_free( stname );
    *pstname = NULL;
    return r;
}

1238 1239 1240 1241 1242 1243 1244 1245
/*
 * 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;
1246 1247
    UINT r;
    LPWSTR full_name = NULL;
1248 1249 1250 1251

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

1252 1253
    r = msi_stream_name( tv, row, &full_name );
    if ( r != ERROR_SUCCESS )
1254
    {
1255 1256
        ERR("fetching stream, error = %d\n", r);
        return r;
1257
    }
1258

1259 1260 1261
    r = db_get_raw_stream( tv->db, full_name, stm );
    if( r )
        ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1262
    msi_free( full_name );
1263 1264 1265 1266

    return r;
}

1267
static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1268
{
1269
    UINT offset, n, i;
1270 1271 1272 1273 1274 1275 1276

    if( !tv->table )
        return ERROR_INVALID_PARAMETER;

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

1277
    if( row >= tv->table->row_count )
1278 1279
        return ERROR_INVALID_PARAMETER;

1280 1281 1282 1283 1284 1285 1286
    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;
    }

1287 1288 1289
    msi_free( tv->columns[col-1].hash_table );
    tv->columns[col-1].hash_table = NULL;

1290
    n = bytes_per_column( tv->db, &tv->columns[col-1] );
1291
    if ( n != 2 && n != 3 && n != 4 )
1292 1293 1294 1295
    {
        ERR("oops! what is %d bytes per column?\n", n );
        return ERROR_FUNCTION_FAILED;
    }
1296

1297 1298
    offset = tv->columns[col-1].offset;
    for ( i = 0; i < n; i++ )
1299
        tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1300

1301 1302 1303
    return ERROR_SUCCESS;
}

1304 1305 1306 1307 1308 1309 1310
static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW *)view;

    if (!tv->table)
        return ERROR_INVALID_PARAMETER;

1311 1312 1313
    if (tv->order)
        row = tv->order->reorder[row];

1314 1315 1316
    return msi_view_get_row(tv->db, view, row, rec);
}

1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
static UINT msi_addstreamW( MSIDATABASE *db, LPCWSTR name, IStream *data )
{
    UINT r;
    MSIQUERY *query = NULL;
    MSIRECORD *rec = NULL;

    static const WCHAR insert[] = {
       'I','N','S','E','R','T',' ','I','N','T','O',' ',
          '`','_','S','t','r','e','a','m','s','`',' ',
         '(','`','N','a','m','e','`',',',
             '`','D','a','t','a','`',')',' ',
         'V','A','L','U','E','S',' ','(','?',',','?',')',0};

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

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

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

    r = MSI_RecordSetIStream( rec, 2, data );
    if ( r != ERROR_SUCCESS )
       goto err;

    r = MSI_DatabaseOpenViewW( db, insert, &query );
    if ( r != ERROR_SUCCESS )
       goto err;

    r = MSI_ViewExecute( query, rec );

err:
    msiobj_release( &query->hdr );
    msiobj_release( &rec->hdr );

    return r;
}

1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
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++ )
    {
1371 1372
        BOOL persistent;

1373 1374 1375 1376
        /* only update the fields specified in the mask */
        if ( !(mask&(1<<i)) )
            continue;

1377
        persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1378
                     (tv->table->data_persistent[row]);
1379 1380 1381 1382 1383 1384 1385
        /* FIXME: should we allow updating keys? */

        val = 0;
        if ( !MSI_RecordIsNull( rec, i + 1 ) )
        {
            if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
            {
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
                IStream *stm;
                LPWSTR stname;

                r = MSI_RecordGetIStream( rec, i + 1, &stm );
                if ( r != ERROR_SUCCESS )
                    return r;

                r = msi_stream_name( tv, row, &stname );
                if ( r != ERROR_SUCCESS )
                {
                    IStream_Release( stm );
                    return r;
                }

                r = msi_addstreamW( tv->db, stname, stm );
                IStream_Release( stm );
                msi_free ( stname );

                if ( r != ERROR_SUCCESS )
                    return r;

1407 1408 1409 1410 1411
                val = 1; /* refers to the first key column */
            }
            else if ( tv->columns[i].type & MSITYPE_STRING )
            {
                LPCWSTR sval = MSI_RecordGetString( rec, i + 1 );
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
                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;
                }

1422 1423
                val = msi_addstringW( tv->db->strings, 0, sval, -1, 1,
                                      persistent ? StringPersistent : StringNonPersistent );
1424
            }
1425
            else if ( 2 == bytes_per_column( tv->db, &tv->columns[ i ] ) )
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
            {
                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;
}

1448
static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1449 1450
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1451
    BYTE **p, *row;
1452
    BOOL *b;
1453
    UINT sz;
1454
    BYTE ***data_ptr;
1455
    BOOL **data_persist_ptr;
1456
    UINT *row_count;
1457

1458
    TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1459 1460 1461 1462

    if( !tv->table )
        return ERROR_INVALID_PARAMETER;

1463
    row = msi_alloc_zero( tv->row_size );
1464 1465 1466
    if( !row )
        return ERROR_NOT_ENOUGH_MEMORY;

1467 1468 1469 1470 1471
    row_count = &tv->table->row_count;
    data_ptr = &tv->table->data;
    data_persist_ptr = &tv->table->data_persistent;
    if (*num == -1)
        *num = tv->table->row_count;
1472

1473
    sz = (*row_count + 1) * sizeof (BYTE*);
1474 1475
    if( *data_ptr )
        p = msi_realloc( *data_ptr, sz );
1476
    else
1477
        p = msi_alloc( sz );
1478
    if( !p )
1479
    {
1480
        msi_free( row );
1481
        return ERROR_NOT_ENOUGH_MEMORY;
1482
    }
1483

1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
    sz = (*row_count + 1) * sizeof (BOOL);
    if( *data_persist_ptr )
        b = msi_realloc( *data_persist_ptr, sz );
    else
        b = msi_alloc( sz );
    if( !b )
    {
        msi_free( row );
        msi_free( p );
        return ERROR_NOT_ENOUGH_MEMORY;
    }

1496 1497
    *data_ptr = p;
    (*data_ptr)[*row_count] = row;
1498 1499 1500 1501

    *data_persist_ptr = b;
    (*data_persist_ptr)[*row_count] = !temporary;

1502
    (*row_count)++;
1503 1504 1505 1506

    return ERROR_SUCCESS;
}

1507
static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1508 1509 1510
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;

1511
    TRACE("%p %p\n", tv, record);
1512

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

1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
    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;
1537
        *rows = tv->table->row_count;
1538 1539 1540 1541 1542 1543
    }

    return ERROR_SUCCESS;
}

static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1544
                UINT n, LPWSTR *name, UINT *type, BOOL *temporary )
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
{
    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;
    }
1559

1560 1561 1562
    if( type )
        *type = tv->columns[n-1].type;

1563 1564 1565
    if( temporary )
        *temporary = tv->columns[n-1].temporary;

1566 1567 1568
    return ERROR_SUCCESS;
}

1569
static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row );
1570 1571 1572

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

1575 1576 1577 1578 1579 1580
    /* 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;

1581 1582 1583
        if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
            TRACE("skipping binary column\n");
        else if ( tv->columns[i].type & MSITYPE_STRING )
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
        {
            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 */
1602
    r = msi_table_find_row( tv, rec, &row );
1603
    if (r == ERROR_SUCCESS)
1604
        return ERROR_FUNCTION_FAILED;
1605 1606

    return ERROR_SUCCESS;
1607 1608
}

1609
static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1610 1611
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1612
    UINT i, r;
1613

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

1616 1617 1618 1619 1620
    /* 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;

1621
    r = table_create_new_row( view, &row, temporary );
1622 1623 1624 1625
    TRACE("insert_row returned %08x\n", r);
    if( r != ERROR_SUCCESS )
        return r;

1626
    /* shift the rows to make room for the new row */
1627
    for (i = tv->table->row_count - 1; i > row; i--)
1628
    {
1629 1630 1631
        memmove(&(tv->table->data[i][0]),
                &(tv->table->data[i - 1][0]), tv->row_size);
        tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1632 1633
    }

1634 1635
    /* Re-set the persistence flag */
    tv->table->data_persistent[row] = !temporary;
1636
    return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1637 1638
}

1639 1640 1641
static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1642
    UINT r, num_rows, num_cols, i;
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655

    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;

1656 1657
    num_rows = tv->table->row_count;
    tv->table->row_count--;
1658

1659 1660 1661 1662 1663 1664 1665
    /* 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;
    }

1666 1667 1668
    if ( row == num_rows - 1 )
        return ERROR_SUCCESS;

1669
    for (i = row + 1; i < num_rows; i++)
1670 1671 1672 1673
    {
        memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
        tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
    }
1674

1675 1676 1677
    return ERROR_SUCCESS;
}

1678
static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1679 1680
{
    MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1681
    UINT r, new_row;
1682 1683 1684 1685 1686 1687 1688 1689

    /* 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;

1690
    r = msi_table_find_row(tv, rec, &new_row);
1691
    if (r != ERROR_SUCCESS)
1692 1693
    {
        ERR("can't find row to modify\n");
1694
        return ERROR_FUNCTION_FAILED;
1695
    }
1696 1697

    /* the row cannot be changed */
1698
    if (row != new_row + 1)
1699 1700
        return ERROR_FUNCTION_FAILED;

1701
    return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1702 1703
}

1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
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);
}

1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
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;
}

1733
static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1734
                          MSIRECORD *rec, UINT row)
1735
{
1736 1737 1738 1739 1740 1741 1742
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    UINT r;

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

    switch (eModifyMode)
    {
1743 1744 1745
    case MSIMODIFY_DELETE:
        r = modify_delete_row( view, rec );
        break;
1746 1747 1748 1749
    case MSIMODIFY_VALIDATE_NEW:
        r = table_validate_new( tv, rec );
        break;

1750 1751 1752 1753
    case MSIMODIFY_INSERT:
        r = table_validate_new( tv, rec );
        if (r != ERROR_SUCCESS)
            break;
1754
        r = TABLE_insert_row( view, rec, -1, FALSE );
1755 1756
        break;

1757 1758 1759 1760
    case MSIMODIFY_INSERT_TEMPORARY:
        r = table_validate_new( tv, rec );
        if (r != ERROR_SUCCESS)
            break;
1761
        r = TABLE_insert_row( view, rec, -1, TRUE );
1762 1763
        break;

1764 1765 1766 1767
    case MSIMODIFY_REFRESH:
        r = msi_refresh_record( view, rec, row );
        break;

1768
    case MSIMODIFY_UPDATE:
1769
        r = msi_table_update( view, rec, row );
1770 1771
        break;

1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
    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;
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
}

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

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

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

1798 1799 1800 1801 1802 1803 1804
    if (tv->order)
    {
        msi_free( tv->order->reorder );
        msi_free( tv->order );
        tv->order = NULL;
    }

1805
    msi_free( tv );
1806 1807 1808 1809

    return ERROR_SUCCESS;
}

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
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;
1827
        UINT num_rows = tv->table->row_count;
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
        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++)
        {
1852 1853 1854
            UINT row_value;

            if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
                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
1875
        entry = (*handle)->next;
1876 1877 1878 1879

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

1880
    *handle = entry;
1881 1882 1883 1884
    if (!entry)
        return ERROR_NO_MORE_ITEMS;

    *row = entry->row;
1885

1886 1887 1888
    return ERROR_SUCCESS;
}

1889 1890 1891
static UINT TABLE_add_ref(struct tagMSIVIEW *view)
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1892
    UINT i;
1893 1894 1895

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

1896 1897 1898 1899 1900 1901
    for (i = 0; i < tv->table->col_count; i++)
    {
        if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
            InterlockedIncrement(&tv->table->colinfo[i].ref_count);
    }

1902 1903 1904
    return InterlockedIncrement(&tv->table->ref_count);
}

1905 1906 1907
static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1908
    MSIRECORD *rec = NULL;
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
    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);
1935
    columns->ops->delete(columns);
1936 1937 1938
    return r;
}

1939 1940 1941 1942
static UINT TABLE_release(struct tagMSIVIEW *view)
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    INT ref = tv->table->ref_count;
1943
    UINT i, r;
1944 1945 1946

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

1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
    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;
            }
        }
    }

1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
    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;
}
1975

1976 1977
static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
                             LPCWSTR column, UINT type, BOOL hold)
1978 1979
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1980
    MSITABLE *msitable;
1981
    MSIRECORD *rec;
1982
    UINT r, i;
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992

    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);

1993
    r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
1994 1995 1996 1997 1998
    if (r != ERROR_SUCCESS)
        goto done;

    msi_update_table_columns(tv->db, table);

1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
    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;
        }
    }

2012 2013 2014 2015 2016
done:
    msiobj_release(&rec->hdr);
    return r;
}

2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
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;

2141 2142 2143
    if (rows == 0)
        return ERROR_SUCCESS;

2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
    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;
}

2171 2172 2173 2174 2175
static UINT TABLE_drop(struct tagMSIVIEW *view)
{
    MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
    MSIVIEW *tables = NULL;
    MSIRECORD *rec = NULL;
2176 2177
    UINT r, row;
    INT i;
2178 2179 2180

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

2181
    for (i = tv->table->col_count - 1; i >= 0; i--)
2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
    {
        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;
}

2218
static const MSIVIEWOPS table_ops =
2219 2220
{
    TABLE_fetch_int,
2221
    TABLE_fetch_stream,
2222
    TABLE_get_row,
2223
    TABLE_set_row,
2224
    TABLE_insert_row,
2225
    TABLE_delete_row,
2226 2227 2228 2229 2230
    TABLE_execute,
    TABLE_close,
    TABLE_get_dimensions,
    TABLE_get_column_info,
    TABLE_modify,
2231
    TABLE_delete,
2232 2233 2234
    TABLE_find_matching_rows,
    TABLE_add_ref,
    TABLE_release,
2235
    TABLE_add_column,
2236
    TABLE_remove_column,
2237
    TABLE_sort,
2238
    TABLE_drop,
2239 2240
};

2241
UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2242 2243
{
    MSITABLEVIEW *tv ;
2244
    UINT r, sz;
2245

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

2249 2250
    TRACE("%p %s %p\n", db, debugstr_w(name), view );

2251 2252
    if ( !lstrcmpW( name, Streams ) )
        return STREAMS_CreateView( db, view );
2253 2254
    else if ( !lstrcmpW( name, Storages ) )
        return STORAGES_CreateView( db, view );
2255

2256
    sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
2257
    tv = msi_alloc_zero( sz );
2258 2259 2260
    if( !tv )
        return ERROR_FUNCTION_FAILED;

2261
    r = get_table( db, name, &tv->table );
2262 2263
    if( r != ERROR_SUCCESS )
    {
2264
        msi_free( tv );
2265 2266
        WARN("table not found\n");
        return r;
2267 2268
    }

2269
    TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2270 2271 2272 2273

    /* fill the structure */
    tv->view.ops = &table_ops;
    tv->db = db;
2274 2275
    tv->columns = tv->table->colinfo;
    tv->num_cols = tv->table->col_count;
2276
    tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count );
2277

2278
    TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2279 2280 2281 2282 2283 2284

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

    return ERROR_SUCCESS;
}
2285 2286 2287 2288 2289 2290

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

2291 2292
    TRACE("%p\n",db);

2293
    r = msi_save_string_table( db->strings, db->storage );
2294 2295
    if( r != ERROR_SUCCESS )
    {
2296
        WARN("failed to save string table r=%08x\n",r);
2297 2298
        return r;
    }
2299

2300
    LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2301 2302 2303
    {
        r = save_table( db, table );
        if( r != ERROR_SUCCESS )
2304
        {
2305
            WARN("failed to save table %s (r=%08x)\n",
2306
                  debugstr_w(table->name), r);
2307
            return r;
2308
        }
2309 2310 2311 2312 2313 2314 2315
    }

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

    return ERROR_SUCCESS;
}
2316

2317 2318
MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
{
2319 2320 2321 2322 2323
    MSITABLE *t;
    UINT r;

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

2324 2325 2326
    if (!table)
        return MSICONDITION_ERROR;

2327 2328
    r = get_table( db, table, &t );
    if (r != ERROR_SUCCESS)
2329 2330
        return MSICONDITION_NONE;

2331
    return t->persistent;
2332 2333
}

2334 2335 2336 2337 2338 2339 2340 2341 2342 2343
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;
}

2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
{
    static const WCHAR szDot[] = { '.', 0 };
    LPWSTR stname = NULL, sval, p;
    DWORD len;
    UINT i, r;

    TRACE("%p %p\n", tv, rec);

    len = lstrlenW( tv->name ) + 1;
    stname = msi_alloc( len*sizeof(WCHAR) );
    if ( !stname )
    {
       r = ERROR_OUTOFMEMORY;
       goto err;
    }

    lstrcpyW( stname, tv->name );

    for ( i = 0; i < tv->num_cols; i++ )
    {
        if ( tv->columns[i].type & MSITYPE_KEY )
        {
            sval = msi_dup_record_field( rec, i + 1 );
            if ( !sval )
            {
                r = ERROR_OUTOFMEMORY;
                goto err;
            }

            len += lstrlenW( szDot ) + lstrlenW ( sval );
            p = msi_realloc ( stname, len*sizeof(WCHAR) );
            if ( !p )
            {
                r = ERROR_OUTOFMEMORY;
                goto err;
            }
            stname = p;

            lstrcatW( stname, szDot );
            lstrcatW( stname, sval );

            msi_free( sval );
        }
        else
            continue;
    }

    *pstname = encode_streamname( FALSE, stname );
    msi_free( stname );

    return ERROR_SUCCESS;

err:
    msi_free ( stname );
    *pstname = NULL;
    return r;
}

2403
static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2404
                                            IStorage *stg,
2405
                                            const BYTE *rawdata, UINT bytes_per_strref )
2406 2407
{
    UINT i, val, ofs = 0;
2408
    USHORT mask;
2409 2410 2411
    MSICOLUMNINFO *columns = tv->columns;
    MSIRECORD *rec;

2412 2413 2414
    mask = rawdata[0] | (rawdata[1] << 8);
    rawdata += 2;

2415 2416 2417 2418
    rec = MSI_CreateRecord( tv->num_cols );
    if( !rec )
        return rec;

2419
    TRACE("row ->\n");
2420 2421 2422 2423 2424 2425 2426 2427
    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;

2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
        if( MSITYPE_IS_BINARY(tv->columns[i].type) )
        {
            LPWSTR encname;
            IStream *stm = NULL;
            UINT r;

            ofs += bytes_per_column( tv->db, &columns[i] );

            r = msi_record_encoded_stream_name( tv, rec, &encname );
            if ( r != ERROR_SUCCESS )
                return NULL;

            r = IStorage_OpenStream( stg, encname, NULL,
                     STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
            msi_free( encname );
            if ( r != ERROR_SUCCESS )
                return NULL;

            MSI_RecordSetStream( rec, i+1, stm );
            TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
        }
        else if( columns[i].type & MSITYPE_STRING )
2450
        {
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
            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
        {
2461
            UINT n = bytes_per_column( tv->db, &columns[i] );
2462
            switch( n )
2463
            {
2464 2465
            case 2:
                val = read_raw_int(rawdata, ofs, n);
2466 2467
                if (val)
                    MSI_RecordSetInteger( rec, i+1, val^0x8000 );
2468
                TRACE(" field %d [0x%04x]\n", i+1, val );
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
                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;
2479
            }
2480
            ofs += n;
2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495
        }
    }
    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 ) )
2496
            TRACE("row -> []\n");
2497
        else if( (sval = MSI_RecordGetString( rec, i )) )
2498
            TRACE("row -> [%s]\n", debugstr_w(sval));
2499
        else
2500
            TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2501 2502 2503
    }
}

2504
static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515
{
    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) );
    }
}

2516
static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
{
    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
2545
        {
2546
            data[i] = MSI_RecordGetInteger( rec, i+1 );
2547 2548 2549 2550

            if (data[i] == MSI_NULL_INTEGER)
                data[i] = 0;
            else if ((tv->columns[i].type&0xff) == 2)
2551 2552 2553 2554
                data[i] += 0x8000;
            else
                data[i] += 0x80000000;
        }
2555 2556 2557 2558
    }
    return data;
}

2559
static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data )
2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595
{
    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;
2596
    for( i = 0; i < tv->table->row_count; i++ )
2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608
    {
        r = msi_row_matches( tv, i, data );
        if( r == ERROR_SUCCESS )
        {
            *row = i;
            break;
        }
    }
    msi_free( data );
    return r;
}

2609 2610 2611 2612 2613 2614
typedef struct
{
    struct list entry;
    LPWSTR name;
} TRANSFORMDATA;

2615
static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2616
                                      string_table *st, TRANSFORMDATA *transform,
2617
                                      UINT bytes_per_strref )
2618
{
2619
    UINT rawsize = 0;
2620
    BYTE *rawdata = NULL;
2621 2622 2623
    MSITABLEVIEW *tv = NULL;
    UINT r, n, sz, i, mask;
    MSIRECORD *rec = NULL;
2624
    UINT colcol = 0;
2625
    WCHAR coltable[32];
2626 2627 2628 2629 2630 2631
    LPWSTR name;

    if (!transform)
        return ERROR_SUCCESS;

    name = transform->name;
2632

2633
    coltable[0] = 0;
2634 2635
    TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );

2636
    /* read the transform data */
2637
    read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2638 2639 2640 2641 2642 2643
    if ( !rawdata )
    {
        TRACE("table %s empty\n", debugstr_w(name) );
        return ERROR_INVALID_TABLE;
    }

2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657
    /* 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;
2658
    for( n=0; n < rawsize;  )
2659
    {
2660
        mask = rawdata[n] | (rawdata[n+1] << 8);
2661 2662 2663 2664 2665 2666 2667

        if (mask&1)
        {
            /*
             * if the low bit is set, columns are continuous and
             * the number of columns is specified in the high byte
             */
2668 2669 2670 2671 2672 2673 2674
            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
2675
                    sz += bytes_per_column( tv->db, &tv->columns[i] );
2676
            }
2677 2678 2679 2680
        }
        else
        {
            /*
2681
             * If the low bit is not set, mask is a bitmask.
2682 2683 2684
             * Excepting for key fields, which are always present,
             *  each bit indicates that a field is present in the transform record.
             *
2685
             * mask == 0 is a special case ... only the keys will be present
2686 2687 2688 2689 2690 2691
             * 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))
2692 2693 2694 2695 2696
                {
                    if( (tv->columns[i].type & MSITYPE_STRING) &&
                        ! MSITYPE_IS_BINARY(tv->columns[i].type) )
                        sz += bytes_per_strref;
                    else
2697
                        sz += bytes_per_column( tv->db, &tv->columns[i] );
2698
                }
2699 2700 2701 2702 2703 2704 2705
            }
        }

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

2710
        rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2711 2712
        if (rec)
        {
2713
            if ( mask & 1 )
2714
            {
2715 2716 2717 2718
                WCHAR table[32];
                DWORD sz = 32;
                UINT number = MSI_NULL_INTEGER;

2719
                TRACE("inserting record\n");
2720 2721 2722

                if (!lstrcmpW(name, szColumns))
                {
2723
                    MSI_RecordGetStringW( rec, 1, table, &sz );
2724
                    number = MSI_RecordGetInteger( rec, 2 );
2725

2726 2727 2728 2729 2730
                    /*
                     * 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 )
2731
                    {
2732 2733 2734 2735 2736 2737 2738 2739 2740
                        /* 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 );
2741
                    }
2742 2743
                }

2744
                r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2745 2746
                if (r != ERROR_SUCCESS)
                    ERR("insert row failed\n");
2747 2748 2749

                if ( number != MSI_NULL_INTEGER && !lstrcmpW(name, szColumns) )
                    msi_update_table_columns( db, table );
2750 2751 2752
            }
            else
            {
2753 2754 2755 2756 2757 2758 2759
                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 )
                {
2760
                    TRACE("modifying row [%d]:\n", row);
2761
                    TABLE_set_row( &tv->view, row, rec, mask );
2762 2763 2764
                }
                else
                {
2765
                    TRACE("deleting row [%d]:\n", row);
2766
                    TABLE_delete_row( &tv->view, row );
2767
                }
2768
            }
2769
            if( TRACE_ON(msidb) ) dump_record( rec );
2770 2771 2772
            msiobj_release( &rec->hdr );
        }

2773
        n += sz;
2774 2775 2776 2777 2778 2779 2780 2781
    }

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

2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
    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 )
{
2792
    struct list transforms;
2793
    IEnumSTATSTG *stgenum = NULL;
2794 2795
    TRANSFORMDATA *transform;
    TRANSFORMDATA *tables = NULL, *columns = NULL;
2796 2797 2798 2799
    HRESULT r;
    STATSTG stat;
    string_table *strings;
    UINT ret = ERROR_FUNCTION_FAILED;
2800
    UINT bytes_per_strref;
2801

2802 2803
    TRACE("%p %p\n", db, stg );

2804
    strings = msi_load_string_table( stg, &bytes_per_strref );
2805 2806 2807 2808 2809 2810 2811
    if( !strings )
        goto end;

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

2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824
    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 );
2825
        CoTaskMemFree( stat.pwcsName );
2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862
        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 );
    }

2863
    /*
Mike McCormack's avatar
Mike McCormack committed
2864
     * Apply _Tables and _Columns transforms first so that
2865 2866
     * the table metadata is correct, and empty tables exist.
     */
2867
    ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2868 2869 2870
    if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
        goto end;

2871
    ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2872 2873 2874
    if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
        goto end;

2875 2876
    ret = ERROR_SUCCESS;

2877
    while ( !list_empty( &transforms ) )
2878
    {
2879
        transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2880

2881 2882 2883 2884 2885 2886
        if ( lstrcmpW( transform->name, szColumns ) &&
             lstrcmpW( transform->name, szTables ) &&
             ret == ERROR_SUCCESS )
        {
            ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
        }
2887

2888 2889 2890
        list_remove( &transform->entry );
        msi_free( transform->name );
        msi_free( transform );
2891 2892
    }

2893
    if ( ret == ERROR_SUCCESS )
2894
        append_storage_to_db( db, stg );
2895

2896 2897 2898 2899 2900 2901 2902 2903
end:
    if ( stgenum )
        IEnumSTATSTG_Release( stgenum );
    if ( strings )
        msi_destroy_stringtable( strings );

    return ret;
}
2904

2905 2906 2907 2908 2909 2910 2911 2912 2913 2914
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 );
}

2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925
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 );
    }
}