push 8b07bf1f08b23b9893a622b47d2be359556765b1
[wine/hacks.git] / dlls / msi / table.c
blobaa37670831cd05da4d38d432638525deb7d837f7
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
4 * Copyright 2002-2005 Mike McCormack for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * 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
21 #include <stdarg.h>
22 #include <assert.h>
24 #define COBJMACROS
25 #define NONAMELESSUNION
26 #define NONAMELESSSTRUCT
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winerror.h"
31 #include "msi.h"
32 #include "msiquery.h"
33 #include "objbase.h"
34 #include "objidl.h"
35 #include "winnls.h"
36 #include "msipriv.h"
37 #include "query.h"
39 #include "wine/debug.h"
40 #include "wine/unicode.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(msidb);
44 #define MSITABLE_HASH_TABLE_SIZE 37
45 #define LONG_STR_BYTES 3
47 typedef struct tagMSICOLUMNHASHENTRY
49 struct tagMSICOLUMNHASHENTRY *next;
50 UINT value;
51 UINT row;
52 } MSICOLUMNHASHENTRY;
54 typedef struct tagMSICOLUMNINFO
56 LPWSTR tablename;
57 UINT number;
58 LPWSTR colname;
59 UINT type;
60 UINT offset;
61 INT ref_count;
62 BOOL temporary;
63 MSICOLUMNHASHENTRY **hash_table;
64 } MSICOLUMNINFO;
66 typedef struct tagMSIORDERINFO
68 UINT *reorder;
69 UINT num_cols;
70 UINT cols[1];
71 } MSIORDERINFO;
73 struct tagMSITABLE
75 BYTE **data;
76 BOOL *data_persistent;
77 UINT row_count;
78 struct list entry;
79 MSICOLUMNINFO *colinfo;
80 UINT col_count;
81 MSICONDITION persistent;
82 INT ref_count;
83 WCHAR name[1];
86 typedef struct tagMSITRANSFORM {
87 struct list entry;
88 IStorage *stg;
89 } MSITRANSFORM;
91 static const WCHAR szStringData[] = {
92 '_','S','t','r','i','n','g','D','a','t','a',0 };
93 static const WCHAR szStringPool[] = {
94 '_','S','t','r','i','n','g','P','o','o','l',0 };
96 /* information for default tables */
97 static WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
98 static WCHAR szTable[] = { 'T','a','b','l','e',0 };
99 static WCHAR szName[] = { 'N','a','m','e',0 };
100 static WCHAR szColumns[] = { '_','C','o','l','u','m','n','s',0 };
101 static WCHAR szNumber[] = { 'N','u','m','b','e','r',0 };
102 static WCHAR szType[] = { 'T','y','p','e',0 };
104 static const MSICOLUMNINFO _Columns_cols[4] = {
105 { szColumns, 1, szTable, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
106 { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2, 2, 0, 0, NULL },
107 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, 0, NULL },
108 { szColumns, 4, szType, MSITYPE_VALID | 2, 6, 0, 0, NULL },
111 static const MSICOLUMNINFO _Tables_cols[1] = {
112 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
115 #define MAX_STREAM_NAME 0x1f
117 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name,
118 MSICOLUMNINFO **pcols, UINT *pcount );
119 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo,
120 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 static UINT table_find_insert_idx (MSIVIEW *view, LPCWSTR name, INT *pidx);
126 static inline UINT bytes_per_column( MSIDATABASE *db, const MSICOLUMNINFO *col )
128 if( MSITYPE_IS_BINARY(col->type) )
129 return 2;
131 if( col->type & MSITYPE_STRING )
132 return db->bytes_per_strref;
134 if( (col->type & 0xff) <= 2)
135 return 2;
137 if( (col->type & 0xff) != 4 )
138 ERR("Invalid column size!\n");
140 return 4;
143 static int utf2mime(int x)
145 if( (x>='0') && (x<='9') )
146 return x-'0';
147 if( (x>='A') && (x<='Z') )
148 return x-'A'+10;
149 if( (x>='a') && (x<='z') )
150 return x-'a'+10+26;
151 if( x=='.' )
152 return 10+26+26;
153 if( x=='_' )
154 return 10+26+26+1;
155 return -1;
158 static LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
160 DWORD count = MAX_STREAM_NAME;
161 DWORD ch, next;
162 LPWSTR out, p;
164 if( !bTable )
165 count = lstrlenW( in )+2;
166 out = msi_alloc( count*sizeof(WCHAR) );
167 p = out;
169 if( bTable )
171 *p++ = 0x4840;
172 count --;
174 while( count -- )
176 ch = *in++;
177 if( !ch )
179 *p = ch;
180 return out;
182 if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
184 ch = utf2mime(ch) + 0x4800;
185 next = *in;
186 if( next && (next<0x80) )
188 next = utf2mime(next);
189 if( next != -1 )
191 next += 0x3ffffc0;
192 ch += (next<<6);
193 in++;
197 *p++ = ch;
199 ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
200 msi_free( out );
201 return NULL;
204 static int mime2utf(int x)
206 if( x<10 )
207 return x + '0';
208 if( x<(10+26))
209 return x - 10 + 'A';
210 if( x<(10+26+26))
211 return x - 10 - 26 + 'a';
212 if( x == (10+26+26) )
213 return '.';
214 return '_';
217 BOOL decode_streamname(LPCWSTR in, LPWSTR out)
219 WCHAR ch;
220 DWORD count = 0;
222 while ( (ch = *in++) )
224 if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
226 if( ch >= 0x4800 )
227 ch = mime2utf(ch-0x4800);
228 else
230 ch -= 0x3800;
231 *out++ = mime2utf(ch&0x3f);
232 count++;
233 ch = mime2utf((ch>>6)&0x3f);
236 *out++ = ch;
237 count++;
239 *out = 0;
240 return count;
243 void enum_stream_names( IStorage *stg )
245 IEnumSTATSTG *stgenum = NULL;
246 HRESULT r;
247 STATSTG stat;
248 ULONG n, count;
249 WCHAR name[0x40];
251 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
252 if( FAILED( r ) )
253 return;
255 n = 0;
256 while( 1 )
258 count = 0;
259 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
260 if( FAILED( r ) || !count )
261 break;
262 decode_streamname( stat.pwcsName, name );
263 TRACE("stream %2d -> %s %s\n", n,
264 debugstr_w(stat.pwcsName), debugstr_w(name) );
265 CoTaskMemFree( stat.pwcsName );
266 n++;
269 IEnumSTATSTG_Release( stgenum );
272 UINT read_stream_data( IStorage *stg, LPCWSTR stname, BOOL table,
273 BYTE **pdata, UINT *psz )
275 HRESULT r;
276 UINT ret = ERROR_FUNCTION_FAILED;
277 VOID *data;
278 ULONG sz, count;
279 IStream *stm = NULL;
280 STATSTG stat;
281 LPWSTR encname;
283 encname = encode_streamname(table, stname);
285 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
287 r = IStorage_OpenStream(stg, encname, NULL,
288 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
289 msi_free( encname );
290 if( FAILED( r ) )
292 WARN("open stream failed r = %08x - empty table?\n", r);
293 return ret;
296 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
297 if( FAILED( r ) )
299 WARN("open stream failed r = %08x!\n", r);
300 goto end;
303 if( stat.cbSize.QuadPart >> 32 )
305 WARN("Too big!\n");
306 goto end;
309 sz = stat.cbSize.QuadPart;
310 data = msi_alloc( sz );
311 if( !data )
313 WARN("couldn't allocate memory r=%08x!\n", r);
314 ret = ERROR_NOT_ENOUGH_MEMORY;
315 goto end;
318 r = IStream_Read(stm, data, sz, &count );
319 if( FAILED( r ) || ( count != sz ) )
321 msi_free( data );
322 WARN("read stream failed r = %08x!\n", r);
323 goto end;
326 *pdata = data;
327 *psz = sz;
328 ret = ERROR_SUCCESS;
330 end:
331 IStream_Release( stm );
333 return ret;
336 static UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
338 LPWSTR encname;
339 HRESULT r;
341 encname = encode_streamname(FALSE, stname);
343 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
345 r = IStorage_OpenStream(db->storage, encname, NULL,
346 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm);
347 if( FAILED( r ) )
349 MSITRANSFORM *transform;
351 LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
353 TRACE("looking for %s in transform storage\n", debugstr_w(stname) );
354 r = IStorage_OpenStream( transform->stg, encname, NULL,
355 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
356 if (SUCCEEDED(r))
357 break;
361 msi_free( encname );
363 return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
366 UINT read_raw_stream_data( MSIDATABASE *db, LPCWSTR stname,
367 USHORT **pdata, UINT *psz )
369 HRESULT r;
370 UINT ret = ERROR_FUNCTION_FAILED;
371 VOID *data;
372 ULONG sz, count;
373 IStream *stm = NULL;
374 STATSTG stat;
376 r = db_get_raw_stream( db, stname, &stm );
377 if( r != ERROR_SUCCESS)
378 return ret;
379 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
380 if( FAILED( r ) )
382 WARN("open stream failed r = %08x!\n", r);
383 goto end;
386 if( stat.cbSize.QuadPart >> 32 )
388 WARN("Too big!\n");
389 goto end;
392 sz = stat.cbSize.QuadPart;
393 data = msi_alloc( sz );
394 if( !data )
396 WARN("couldn't allocate memory r=%08x!\n", r);
397 ret = ERROR_NOT_ENOUGH_MEMORY;
398 goto end;
401 r = IStream_Read(stm, data, sz, &count );
402 if( FAILED( r ) || ( count != sz ) )
404 msi_free( data );
405 WARN("read stream failed r = %08x!\n", r);
406 goto end;
409 *pdata = data;
410 *psz = sz;
411 ret = ERROR_SUCCESS;
413 end:
414 IStream_Release( stm );
416 return ret;
419 UINT write_stream_data( IStorage *stg, LPCWSTR stname,
420 LPCVOID data, UINT sz, BOOL bTable )
422 HRESULT r;
423 UINT ret = ERROR_FUNCTION_FAILED;
424 ULONG count;
425 IStream *stm = NULL;
426 ULARGE_INTEGER size;
427 LARGE_INTEGER pos;
428 LPWSTR encname;
430 encname = encode_streamname(bTable, stname );
431 r = IStorage_OpenStream( stg, encname, NULL,
432 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
433 if( FAILED(r) )
435 r = IStorage_CreateStream( stg, encname,
436 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
438 msi_free( encname );
439 if( FAILED( r ) )
441 WARN("open stream failed r = %08x\n", r);
442 return ret;
445 size.QuadPart = sz;
446 r = IStream_SetSize( stm, size );
447 if( FAILED( r ) )
449 WARN("Failed to SetSize\n");
450 goto end;
453 pos.QuadPart = 0;
454 r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
455 if( FAILED( r ) )
457 WARN("Failed to Seek\n");
458 goto end;
461 if (sz)
463 r = IStream_Write(stm, data, sz, &count );
464 if( FAILED( r ) || ( count != sz ) )
466 WARN("Failed to Write\n");
467 goto end;
471 ret = ERROR_SUCCESS;
473 end:
474 IStream_Release( stm );
476 return ret;
479 static void free_table( MSITABLE *table )
481 UINT i;
482 for( i=0; i<table->row_count; i++ )
483 msi_free( table->data[i] );
484 msi_free( table->data );
485 msi_free( table->data_persistent );
486 msi_free_colinfo( table->colinfo, table->col_count );
487 msi_free( table->colinfo );
488 msi_free( table );
491 static UINT msi_table_get_row_size( MSIDATABASE *db,const MSICOLUMNINFO *cols,
492 UINT count )
494 const MSICOLUMNINFO *last_col = &cols[count-1];
495 if (!count)
496 return 0;
497 return last_col->offset + bytes_per_column( db, last_col );
500 /* add this table to the list of cached tables in the database */
501 static UINT read_table_from_storage( MSIDATABASE *db, MSITABLE *t, IStorage *stg )
503 BYTE *rawdata = NULL;
504 UINT rawsize = 0, i, j, row_size = 0;
506 TRACE("%s\n",debugstr_w(t->name));
508 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count );
510 /* if we can't read the table, just assume that it's empty */
511 read_stream_data( stg, t->name, TRUE, &rawdata, &rawsize );
512 if( !rawdata )
513 return ERROR_SUCCESS;
515 TRACE("Read %d bytes\n", rawsize );
517 if( rawsize % row_size )
519 WARN("Table size is invalid %d/%d\n", rawsize, row_size );
520 goto err;
523 t->row_count = rawsize / row_size;
524 t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
525 if( !t->data )
526 goto err;
527 t->data_persistent = msi_alloc_zero( t->row_count * sizeof(BOOL));
528 if ( !t->data_persistent )
529 goto err;
531 /* transpose all the data */
532 TRACE("Transposing data from %d rows\n", t->row_count );
533 for( i=0; i<t->row_count; i++ )
535 t->data[i] = msi_alloc( row_size );
536 if( !t->data[i] )
537 goto err;
538 t->data_persistent[i] = TRUE;
540 for( j=0; j<t->col_count; j++ )
542 UINT ofs = t->colinfo[j].offset;
543 UINT n = bytes_per_column( db, &t->colinfo[j] );
544 UINT k;
546 if ( n != 2 && n != 3 && n != 4 )
548 ERR("oops - unknown column width %d\n", n);
549 goto err;
552 for ( k = 0; k < n; k++ )
553 t->data[i][ofs + k] = rawdata[ofs*t->row_count + i * n + k];
557 msi_free( rawdata );
558 return ERROR_SUCCESS;
559 err:
560 msi_free( rawdata );
561 return ERROR_FUNCTION_FAILED;
564 void free_cached_tables( MSIDATABASE *db )
566 while( !list_empty( &db->tables ) )
568 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
570 list_remove( &t->entry );
571 free_table( t );
575 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
577 MSITABLE *t;
579 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
580 if( !lstrcmpW( name, t->name ) )
581 return t;
583 return NULL;
586 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
588 UINT r, column_count = 0;
589 MSICOLUMNINFO *columns;
591 /* get the number of columns in this table */
592 column_count = 0;
593 r = get_tablecolumns( db, name, NULL, &column_count );
594 if( r != ERROR_SUCCESS )
595 return r;
597 *pcount = column_count;
599 /* if there's no columns, there's no table */
600 if( column_count == 0 )
601 return ERROR_INVALID_PARAMETER;
603 TRACE("Table %s found\n", debugstr_w(name) );
605 columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO) );
606 if( !columns )
607 return ERROR_FUNCTION_FAILED;
609 r = get_tablecolumns( db, name, columns, &column_count );
610 if( r != ERROR_SUCCESS )
612 msi_free( columns );
613 return ERROR_FUNCTION_FAILED;
616 *pcols = columns;
618 return r;
621 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
622 MSICONDITION persistent, MSITABLE **table_ret)
624 UINT r, nField;
625 MSIVIEW *tv = NULL;
626 MSIRECORD *rec = NULL;
627 column_info *col;
628 MSITABLE *table;
629 UINT i;
630 INT idx;
632 /* only add tables that don't exist already */
633 if( TABLE_Exists(db, name ) )
635 WARN("table %s exists\n", debugstr_w(name));
636 return ERROR_BAD_QUERY_SYNTAX;
639 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
640 if( !table )
641 return ERROR_FUNCTION_FAILED;
643 table->ref_count = 1;
644 table->row_count = 0;
645 table->data = NULL;
646 table->data_persistent = NULL;
647 table->colinfo = NULL;
648 table->col_count = 0;
649 table->persistent = persistent;
650 lstrcpyW( table->name, name );
652 for( col = col_info; col; col = col->next )
653 table->col_count++;
655 table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
656 if (!table->colinfo)
658 free_table( table );
659 return ERROR_FUNCTION_FAILED;
662 for( i = 0, col = col_info; col; i++, col = col->next )
664 table->colinfo[ i ].tablename = strdupW( col->table );
665 table->colinfo[ i ].number = i + 1;
666 table->colinfo[ i ].colname = strdupW( col->column );
667 table->colinfo[ i ].type = col->type;
668 table->colinfo[ i ].offset = 0;
669 table->colinfo[ i ].ref_count = 0;
670 table->colinfo[ i ].hash_table = NULL;
671 table->colinfo[ i ].temporary = col->temporary;
673 table_calc_column_offsets( db, table->colinfo, table->col_count);
675 r = TABLE_CreateView( db, szTables, &tv );
676 TRACE("CreateView returned %x\n", r);
677 if( r )
679 free_table( table );
680 return r;
683 r = tv->ops->execute( tv, 0 );
684 TRACE("tv execute returned %x\n", r);
685 if( r )
686 goto err;
688 rec = MSI_CreateRecord( 1 );
689 if( !rec )
690 goto err;
692 r = MSI_RecordSetStringW( rec, 1, name );
693 if( r )
694 goto err;
696 r = table_find_insert_idx (tv, name, &idx);
697 if (r != ERROR_SUCCESS)
698 idx = -1;
700 r = tv->ops->insert_row( tv, rec, idx, persistent == MSICONDITION_FALSE );
701 TRACE("insert_row returned %x\n", r);
702 if( r )
703 goto err;
705 tv->ops->delete( tv );
706 tv = NULL;
708 msiobj_release( &rec->hdr );
709 rec = NULL;
711 if( persistent != MSICONDITION_FALSE )
713 /* add each column to the _Columns table */
714 r = TABLE_CreateView( db, szColumns, &tv );
715 if( r )
716 return r;
718 r = tv->ops->execute( tv, 0 );
719 TRACE("tv execute returned %x\n", r);
720 if( r )
721 goto err;
723 rec = MSI_CreateRecord( 4 );
724 if( !rec )
725 goto err;
727 r = MSI_RecordSetStringW( rec, 1, name );
728 if( r )
729 goto err;
732 * need to set the table, column number, col name and type
733 * for each column we enter in the table
735 nField = 1;
736 for( col = col_info; col; col = col->next )
738 r = MSI_RecordSetInteger( rec, 2, nField );
739 if( r )
740 goto err;
742 r = MSI_RecordSetStringW( rec, 3, col->column );
743 if( r )
744 goto err;
746 r = MSI_RecordSetInteger( rec, 4, col->type );
747 if( r )
748 goto err;
750 r = table_find_insert_idx (tv, name, &idx);
751 if (r != ERROR_SUCCESS)
752 idx = -1;
754 r = tv->ops->insert_row( tv, rec, idx, FALSE );
755 if( r )
756 goto err;
758 nField++;
760 if( !col )
761 r = ERROR_SUCCESS;
764 err:
765 if (rec)
766 msiobj_release( &rec->hdr );
767 /* FIXME: remove values from the string table on error */
768 if( tv )
769 tv->ops->delete( tv );
771 if (r == ERROR_SUCCESS)
773 list_add_head( &db->tables, &table->entry );
774 *table_ret = table;
776 else
777 free_table( table );
779 return r;
782 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
784 MSITABLE *table;
785 UINT r;
787 /* first, see if the table is cached */
788 table = find_cached_table( db, name );
789 if( table )
791 *table_ret = table;
792 return ERROR_SUCCESS;
795 /* nonexistent tables should be interpreted as empty tables */
796 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
797 if( !table )
798 return ERROR_FUNCTION_FAILED;
800 table->row_count = 0;
801 table->data = NULL;
802 table->data_persistent = NULL;
803 table->colinfo = NULL;
804 table->col_count = 0;
805 table->persistent = MSICONDITION_TRUE;
806 lstrcpyW( table->name, name );
808 if ( !lstrcmpW(name, szTables) || !lstrcmpW(name, szColumns) )
809 table->persistent = MSICONDITION_NONE;
811 r = table_get_column_info( db, name, &table->colinfo, &table->col_count);
812 if (r != ERROR_SUCCESS)
814 free_table ( table );
815 return r;
818 r = read_table_from_storage( db, table, db->storage );
819 if( r != ERROR_SUCCESS )
821 free_table( table );
822 return r;
825 list_add_head( &db->tables, &table->entry );
826 *table_ret = table;
827 return ERROR_SUCCESS;
830 static UINT save_table( MSIDATABASE *db, const MSITABLE *t )
832 BYTE *rawdata = NULL, *p;
833 UINT rawsize, r, i, j, row_size;
835 /* Nothing to do for non-persistent tables */
836 if( t->persistent == MSICONDITION_FALSE )
837 return ERROR_SUCCESS;
839 TRACE("Saving %s\n", debugstr_w( t->name ) );
841 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count );
843 rawsize = t->row_count * row_size;
844 rawdata = msi_alloc_zero( rawsize );
845 if( !rawdata )
847 r = ERROR_NOT_ENOUGH_MEMORY;
848 goto err;
851 rawsize = 0;
852 p = rawdata;
853 for( i=0; i<t->col_count; i++ )
855 for( j=0; j<t->row_count; j++ )
857 UINT offset = t->colinfo[i].offset;
859 if (!t->data_persistent[j]) continue;
860 if (i == 0)
861 rawsize += row_size;
863 *p++ = t->data[j][offset];
864 *p++ = t->data[j][offset + 1];
865 if( 4 == bytes_per_column( db, &t->colinfo[i] ) )
867 *p++ = t->data[j][offset + 2];
868 *p++ = t->data[j][offset + 3];
873 TRACE("writing %d bytes\n", rawsize);
874 r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
876 err:
877 msi_free( rawdata );
879 return r;
882 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo,
883 DWORD count )
885 DWORD i;
887 for( i=0; colinfo && (i<count); i++ )
889 assert( (i+1) == colinfo[ i ].number );
890 if (i)
891 colinfo[i].offset = colinfo[ i - 1 ].offset
892 + bytes_per_column( db, &colinfo[ i - 1 ] );
893 else
894 colinfo[i].offset = 0;
895 TRACE("column %d is [%s] with type %08x ofs %d\n",
896 colinfo[i].number, debugstr_w(colinfo[i].colname),
897 colinfo[i].type, colinfo[i].offset);
901 static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name,
902 MSICOLUMNINFO *colinfo, UINT *sz)
904 const MSICOLUMNINFO *p;
905 DWORD i, n;
907 TRACE("%s\n", debugstr_w(name));
909 if (!lstrcmpW( name, szTables ))
911 p = _Tables_cols;
912 n = 1;
914 else if (!lstrcmpW( name, szColumns ))
916 p = _Columns_cols;
917 n = 4;
919 else
920 return ERROR_FUNCTION_FAILED;
922 /* duplicate the string data so we can free it in msi_free_colinfo */
923 for (i=0; i<n; i++)
925 if (colinfo && (i < *sz) )
927 colinfo[i] = p[i];
928 colinfo[i].tablename = strdupW( p[i].tablename );
929 colinfo[i].colname = strdupW( p[i].colname );
931 if( colinfo && (i >= *sz) )
932 break;
934 table_calc_column_offsets( db, colinfo, n );
935 *sz = n;
936 return ERROR_SUCCESS;
939 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
941 UINT i;
943 for( i=0; i<count; i++ )
945 msi_free( colinfo[i].tablename );
946 msi_free( colinfo[i].colname );
947 msi_free( colinfo[i].hash_table );
951 static LPWSTR msi_makestring( const MSIDATABASE *db, UINT stringid)
953 return strdupW(msi_string_lookup_id( db->strings, stringid ));
956 static UINT read_table_int(BYTE *const *data, UINT row, UINT col, UINT bytes)
958 UINT ret = 0, i;
960 for (i = 0; i < bytes; i++)
961 ret += (data[row][col + i] << i * 8);
963 return ret;
966 static UINT get_tablecolumns( MSIDATABASE *db,
967 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
969 UINT r, i, n=0, table_id, count, maxcount = *sz;
970 MSITABLE *table = NULL;
972 TRACE("%s\n", debugstr_w(szTableName));
974 /* first check if there is a default table with that name */
975 r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
976 if( ( r == ERROR_SUCCESS ) && *sz )
977 return r;
979 r = get_table( db, szColumns, &table );
980 if( r != ERROR_SUCCESS )
982 ERR("couldn't load _Columns table\n");
983 return ERROR_FUNCTION_FAILED;
986 /* convert table and column names to IDs from the string table */
987 r = msi_string2idW( db->strings, szTableName, &table_id );
988 if( r != ERROR_SUCCESS )
990 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
991 return r;
994 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
996 /* Note: _Columns table doesn't have non-persistent data */
998 /* if maxcount is non-zero, assume it's exactly right for this table */
999 memset( colinfo, 0, maxcount*sizeof(*colinfo) );
1000 count = table->row_count;
1001 for( i=0; i<count; i++ )
1003 if( read_table_int(table->data, i, 0, db->bytes_per_strref) != table_id )
1004 continue;
1005 if( colinfo )
1007 UINT id = read_table_int(table->data, i, table->colinfo[2].offset, db->bytes_per_strref);
1008 UINT col = read_table_int(table->data, i, table->colinfo[1].offset, sizeof(USHORT)) - (1<<15);
1010 /* check the column number is in range */
1011 if (col<1 || col>maxcount)
1013 ERR("column %d out of range\n", col);
1014 continue;
1017 /* check if this column was already set */
1018 if (colinfo[ col - 1 ].number)
1020 ERR("duplicate column %d\n", col);
1021 continue;
1024 colinfo[ col - 1 ].tablename = msi_makestring( db, table_id );
1025 colinfo[ col - 1 ].number = col;
1026 colinfo[ col - 1 ].colname = msi_makestring( db, id );
1027 colinfo[ col - 1 ].type = read_table_int(table->data, i,
1028 table->colinfo[3].offset,
1029 sizeof(USHORT)) - (1<<15);
1030 colinfo[ col - 1 ].offset = 0;
1031 colinfo[ col - 1 ].ref_count = 0;
1032 colinfo[ col - 1 ].hash_table = NULL;
1034 n++;
1037 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
1039 if (colinfo && n != maxcount)
1041 ERR("missing column in table %s\n", debugstr_w(szTableName));
1042 msi_free_colinfo(colinfo, maxcount );
1043 return ERROR_FUNCTION_FAILED;
1046 table_calc_column_offsets( db, colinfo, n );
1047 *sz = n;
1049 return ERROR_SUCCESS;
1052 static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
1054 MSITABLE *table;
1055 UINT size, offset, old_count;
1056 UINT n;
1058 table = find_cached_table( db, name );
1059 old_count = table->col_count;
1060 msi_free( table->colinfo );
1061 table->colinfo = NULL;
1063 table_get_column_info( db, name, &table->colinfo, &table->col_count );
1064 if (!table->col_count)
1065 return;
1067 size = msi_table_get_row_size( db, table->colinfo, table->col_count );
1068 offset = table->colinfo[table->col_count - 1].offset;
1070 for ( n = 0; n < table->row_count; n++ )
1072 table->data[n] = msi_realloc( table->data[n], size );
1073 if (old_count < table->col_count)
1074 memset( &table->data[n][offset], 0, size - offset );
1078 /* try to find the table name in the _Tables table */
1079 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
1081 UINT r, table_id = 0, i, count;
1082 MSITABLE *table = NULL;
1084 static const WCHAR szStreams[] = {'_','S','t','r','e','a','m','s',0};
1085 static const WCHAR szStorages[] = {'_','S','t','o','r','a','g','e','s',0};
1087 if( !lstrcmpW( name, szTables ) || !lstrcmpW( name, szColumns ) ||
1088 !lstrcmpW( name, szStreams ) || !lstrcmpW( name, szStorages ) )
1089 return TRUE;
1091 r = msi_string2idW( db->strings, name, &table_id );
1092 if( r != ERROR_SUCCESS )
1094 TRACE("Couldn't find id for %s\n", debugstr_w(name));
1095 return FALSE;
1098 r = get_table( db, szTables, &table );
1099 if( r != ERROR_SUCCESS )
1101 ERR("table %s not available\n", debugstr_w(szTables));
1102 return FALSE;
1105 count = table->row_count;
1106 for( i=0; i<count; i++ )
1107 if( table->data[ i ][ 0 ] == table_id )
1108 return TRUE;
1110 return FALSE;
1113 /* below is the query interface to a table */
1115 typedef struct tagMSITABLEVIEW
1117 MSIVIEW view;
1118 MSIDATABASE *db;
1119 MSITABLE *table;
1120 MSICOLUMNINFO *columns;
1121 MSIORDERINFO *order;
1122 UINT num_cols;
1123 UINT row_size;
1124 WCHAR name[1];
1125 } MSITABLEVIEW;
1127 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1129 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1130 UINT offset, n;
1132 if( !tv->table )
1133 return ERROR_INVALID_PARAMETER;
1135 if( (col==0) || (col>tv->num_cols) )
1136 return ERROR_INVALID_PARAMETER;
1138 /* how many rows are there ? */
1139 if( row >= tv->table->row_count )
1140 return ERROR_NO_MORE_ITEMS;
1142 if( tv->columns[col-1].offset >= tv->row_size )
1144 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1145 ERR("%p %p\n", tv, tv->columns );
1146 return ERROR_FUNCTION_FAILED;
1149 if (tv->order)
1150 row = tv->order->reorder[row];
1152 n = bytes_per_column( tv->db, &tv->columns[col-1] );
1153 if (n != 2 && n != 3 && n != 4)
1155 ERR("oops! what is %d bytes per column?\n", n );
1156 return ERROR_FUNCTION_FAILED;
1159 offset = tv->columns[col-1].offset;
1160 *val = read_table_int(tv->table->data, row, offset, n);
1162 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1164 return ERROR_SUCCESS;
1167 static UINT msi_stream_name( const MSITABLEVIEW *tv, UINT row, LPWSTR *pstname )
1169 LPWSTR p, stname = NULL;
1170 UINT i, r, type, ival;
1171 DWORD len;
1172 LPCWSTR sval;
1173 MSIVIEW *view = (MSIVIEW *) tv;
1175 TRACE("%p %d\n", tv, row);
1177 len = lstrlenW( tv->name ) + 1;
1178 stname = msi_alloc( len*sizeof(WCHAR) );
1179 if ( !stname )
1181 r = ERROR_OUTOFMEMORY;
1182 goto err;
1185 lstrcpyW( stname, tv->name );
1187 for ( i = 0; i < tv->num_cols; i++ )
1189 type = tv->columns[i].type;
1190 if ( type & MSITYPE_KEY )
1192 r = TABLE_fetch_int( view, row, i+1, &ival );
1193 if ( r != ERROR_SUCCESS )
1194 goto err;
1196 if ( tv->columns[i].type & MSITYPE_STRING )
1198 sval = msi_string_lookup_id( tv->db->strings, ival );
1199 if ( !sval )
1201 r = ERROR_INVALID_PARAMETER;
1202 goto err;
1205 else
1207 static const WCHAR fmt[] = { '%','d',0 };
1208 WCHAR number[0x20];
1209 UINT n = bytes_per_column( tv->db, &tv->columns[i] );
1211 switch( n )
1213 case 2:
1214 sprintfW( number, fmt, ival^0x8000 );
1215 break;
1216 case 4:
1217 sprintfW( number, fmt, ival^0x80000000 );
1218 break;
1219 default:
1220 ERR( "oops - unknown column width %d\n", n );
1221 r = ERROR_FUNCTION_FAILED;
1222 goto err;
1224 sval = number;
1227 len += lstrlenW( szDot ) + lstrlenW( sval );
1228 p = msi_realloc ( stname, len*sizeof(WCHAR) );
1229 if ( !p )
1231 r = ERROR_OUTOFMEMORY;
1232 goto err;
1234 stname = p;
1236 lstrcatW( stname, szDot );
1237 lstrcatW( stname, sval );
1239 else
1240 continue;
1243 *pstname = stname;
1244 return ERROR_SUCCESS;
1246 err:
1247 msi_free( stname );
1248 *pstname = NULL;
1249 return r;
1253 * We need a special case for streams, as we need to reference column with
1254 * the name of the stream in the same table, and the table name
1255 * which may not be available at higher levels of the query
1257 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1259 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1260 UINT r;
1261 LPWSTR full_name = NULL;
1263 if( !view->ops->fetch_int )
1264 return ERROR_INVALID_PARAMETER;
1266 r = msi_stream_name( tv, row, &full_name );
1267 if ( r != ERROR_SUCCESS )
1269 ERR("fetching stream, error = %d\n", r);
1270 return r;
1273 r = db_get_raw_stream( tv->db, full_name, stm );
1274 if( r )
1275 ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1276 msi_free( full_name );
1278 return r;
1281 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1283 UINT offset, n, i;
1285 if( !tv->table )
1286 return ERROR_INVALID_PARAMETER;
1288 if( (col==0) || (col>tv->num_cols) )
1289 return ERROR_INVALID_PARAMETER;
1291 if( row >= tv->table->row_count )
1292 return ERROR_INVALID_PARAMETER;
1294 if( tv->columns[col-1].offset >= tv->row_size )
1296 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1297 ERR("%p %p\n", tv, tv->columns );
1298 return ERROR_FUNCTION_FAILED;
1301 msi_free( tv->columns[col-1].hash_table );
1302 tv->columns[col-1].hash_table = NULL;
1304 n = bytes_per_column( tv->db, &tv->columns[col-1] );
1305 if ( n != 2 && n != 3 && n != 4 )
1307 ERR("oops! what is %d bytes per column?\n", n );
1308 return ERROR_FUNCTION_FAILED;
1311 offset = tv->columns[col-1].offset;
1312 for ( i = 0; i < n; i++ )
1313 tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1315 return ERROR_SUCCESS;
1318 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1320 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1322 if (!tv->table)
1323 return ERROR_INVALID_PARAMETER;
1325 if (tv->order)
1326 row = tv->order->reorder[row];
1328 return msi_view_get_row(tv->db, view, row, rec);
1331 static UINT msi_addstreamW( MSIDATABASE *db, LPCWSTR name, IStream *data )
1333 UINT r;
1334 MSIQUERY *query = NULL;
1335 MSIRECORD *rec = NULL;
1337 static const WCHAR insert[] = {
1338 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1339 '`','_','S','t','r','e','a','m','s','`',' ',
1340 '(','`','N','a','m','e','`',',',
1341 '`','D','a','t','a','`',')',' ',
1342 'V','A','L','U','E','S',' ','(','?',',','?',')',0};
1344 TRACE("%p %s %p\n", db, debugstr_w(name), data);
1346 rec = MSI_CreateRecord( 2 );
1347 if ( !rec )
1348 return ERROR_OUTOFMEMORY;
1350 r = MSI_RecordSetStringW( rec, 1, name );
1351 if ( r != ERROR_SUCCESS )
1352 goto err;
1354 r = MSI_RecordSetIStream( rec, 2, data );
1355 if ( r != ERROR_SUCCESS )
1356 goto err;
1358 r = MSI_DatabaseOpenViewW( db, insert, &query );
1359 if ( r != ERROR_SUCCESS )
1360 goto err;
1362 r = MSI_ViewExecute( query, rec );
1364 err:
1365 msiobj_release( &query->hdr );
1366 msiobj_release( &rec->hdr );
1368 return r;
1371 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1373 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1374 UINT i, val, r = ERROR_SUCCESS;
1376 if ( !tv->table )
1377 return ERROR_INVALID_PARAMETER;
1379 /* test if any of the mask bits are invalid */
1380 if ( mask >= (1<<tv->num_cols) )
1381 return ERROR_INVALID_PARAMETER;
1383 for ( i = 0; i < tv->num_cols; i++ )
1385 BOOL persistent;
1387 /* only update the fields specified in the mask */
1388 if ( !(mask&(1<<i)) )
1389 continue;
1391 persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1392 (tv->table->data_persistent[row]);
1393 /* FIXME: should we allow updating keys? */
1395 val = 0;
1396 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1398 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1400 IStream *stm;
1401 LPWSTR stname;
1403 r = MSI_RecordGetIStream( rec, i + 1, &stm );
1404 if ( r != ERROR_SUCCESS )
1405 return r;
1407 r = msi_stream_name( tv, row, &stname );
1408 if ( r != ERROR_SUCCESS )
1410 IStream_Release( stm );
1411 return r;
1414 r = msi_addstreamW( tv->db, stname, stm );
1415 IStream_Release( stm );
1416 msi_free ( stname );
1418 if ( r != ERROR_SUCCESS )
1419 return r;
1421 val = 1; /* refers to the first key column */
1423 else if ( tv->columns[i].type & MSITYPE_STRING )
1425 LPCWSTR sval = MSI_RecordGetString( rec, i + 1 );
1426 UINT ival, x;
1428 r = msi_string2idW(tv->db->strings, sval, &ival);
1429 if (r == ERROR_SUCCESS)
1431 TABLE_fetch_int(&tv->view, row, i + 1, &x);
1432 if (ival == x)
1433 continue;
1436 val = msi_addstringW( tv->db->strings, 0, sval, -1, 1,
1437 persistent ? StringPersistent : StringNonPersistent );
1439 else if ( 2 == bytes_per_column( tv->db, &tv->columns[ i ] ) )
1441 val = 0x8000 + MSI_RecordGetInteger( rec, i + 1 );
1442 if ( val & 0xffff0000 )
1444 ERR("field %u value %d out of range\n", i+1, val - 0x8000 );
1445 return ERROR_FUNCTION_FAILED;
1448 else
1450 INT ival = MSI_RecordGetInteger( rec, i + 1 );
1451 val = ival ^ 0x80000000;
1455 r = TABLE_set_int( tv, row, i+1, val );
1456 if ( r != ERROR_SUCCESS )
1457 break;
1459 return r;
1462 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1464 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1465 BYTE **p, *row;
1466 BOOL *b;
1467 UINT sz;
1468 BYTE ***data_ptr;
1469 BOOL **data_persist_ptr;
1470 UINT *row_count;
1472 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1474 if( !tv->table )
1475 return ERROR_INVALID_PARAMETER;
1477 row = msi_alloc_zero( tv->row_size );
1478 if( !row )
1479 return ERROR_NOT_ENOUGH_MEMORY;
1481 row_count = &tv->table->row_count;
1482 data_ptr = &tv->table->data;
1483 data_persist_ptr = &tv->table->data_persistent;
1484 if (*num == -1)
1485 *num = tv->table->row_count;
1487 sz = (*row_count + 1) * sizeof (BYTE*);
1488 if( *data_ptr )
1489 p = msi_realloc( *data_ptr, sz );
1490 else
1491 p = msi_alloc( sz );
1492 if( !p )
1494 msi_free( row );
1495 return ERROR_NOT_ENOUGH_MEMORY;
1498 sz = (*row_count + 1) * sizeof (BOOL);
1499 if( *data_persist_ptr )
1500 b = msi_realloc( *data_persist_ptr, sz );
1501 else
1502 b = msi_alloc( sz );
1503 if( !b )
1505 msi_free( row );
1506 msi_free( p );
1507 return ERROR_NOT_ENOUGH_MEMORY;
1510 *data_ptr = p;
1511 (*data_ptr)[*row_count] = row;
1513 *data_persist_ptr = b;
1514 (*data_persist_ptr)[*row_count] = !temporary;
1516 (*row_count)++;
1518 return ERROR_SUCCESS;
1521 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1523 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1525 TRACE("%p %p\n", tv, record);
1527 TRACE("There are %d columns\n", tv->num_cols );
1529 return ERROR_SUCCESS;
1532 static UINT TABLE_close( struct tagMSIVIEW *view )
1534 TRACE("%p\n", view );
1536 return ERROR_SUCCESS;
1539 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1541 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1543 TRACE("%p %p %p\n", view, rows, cols );
1545 if( cols )
1546 *cols = tv->num_cols;
1547 if( rows )
1549 if( !tv->table )
1550 return ERROR_INVALID_PARAMETER;
1551 *rows = tv->table->row_count;
1554 return ERROR_SUCCESS;
1557 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1558 UINT n, LPWSTR *name, UINT *type, BOOL *temporary )
1560 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1562 TRACE("%p %d %p %p\n", tv, n, name, type );
1564 if( ( n == 0 ) || ( n > tv->num_cols ) )
1565 return ERROR_INVALID_PARAMETER;
1567 if( name )
1569 *name = strdupW( tv->columns[n-1].colname );
1570 if( !*name )
1571 return ERROR_FUNCTION_FAILED;
1574 if( type )
1575 *type = tv->columns[n-1].type;
1577 if( temporary )
1578 *temporary = tv->columns[n-1].temporary;
1580 return ERROR_SUCCESS;
1583 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row );
1585 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec )
1587 UINT r, row, i;
1589 /* check there's no null values where they're not allowed */
1590 for( i = 0; i < tv->num_cols; i++ )
1592 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1593 continue;
1595 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1596 TRACE("skipping binary column\n");
1597 else if ( tv->columns[i].type & MSITYPE_STRING )
1599 LPCWSTR str;
1601 str = MSI_RecordGetString( rec, i+1 );
1602 if (str == NULL || str[0] == 0)
1603 return ERROR_INVALID_DATA;
1605 else
1607 UINT n;
1609 n = MSI_RecordGetInteger( rec, i+1 );
1610 if (n == MSI_NULL_INTEGER)
1611 return ERROR_INVALID_DATA;
1615 /* check there's no duplicate keys */
1616 r = msi_table_find_row( tv, rec, &row );
1617 if (r == ERROR_SUCCESS)
1618 return ERROR_FUNCTION_FAILED;
1620 return ERROR_SUCCESS;
1623 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1625 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1626 UINT i, r;
1628 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1630 /* check that the key is unique - can we find a matching row? */
1631 r = table_validate_new( tv, rec );
1632 if( r != ERROR_SUCCESS )
1633 return ERROR_FUNCTION_FAILED;
1635 r = table_create_new_row( view, &row, temporary );
1636 TRACE("insert_row returned %08x\n", r);
1637 if( r != ERROR_SUCCESS )
1638 return r;
1640 /* shift the rows to make room for the new row */
1641 for (i = tv->table->row_count - 1; i > row; i--)
1643 memmove(&(tv->table->data[i][0]),
1644 &(tv->table->data[i - 1][0]), tv->row_size);
1645 tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1648 /* Re-set the persistence flag */
1649 tv->table->data_persistent[row] = !temporary;
1650 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1653 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1655 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1656 UINT r, num_rows, num_cols, i;
1658 TRACE("%p %d\n", tv, row);
1660 if ( !tv->table )
1661 return ERROR_INVALID_PARAMETER;
1663 r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1664 if ( r != ERROR_SUCCESS )
1665 return r;
1667 if ( row >= num_rows )
1668 return ERROR_FUNCTION_FAILED;
1670 num_rows = tv->table->row_count;
1671 tv->table->row_count--;
1673 /* reset the hash tables */
1674 for (i = 0; i < tv->num_cols; i++)
1676 msi_free( tv->columns[i].hash_table );
1677 tv->columns[i].hash_table = NULL;
1680 if ( row == num_rows - 1 )
1681 return ERROR_SUCCESS;
1683 for (i = row + 1; i < num_rows; i++)
1685 memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
1686 tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
1689 return ERROR_SUCCESS;
1692 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1694 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1695 UINT r, new_row;
1697 /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1698 * sets the fetched record apart from other records
1701 if (!tv->table)
1702 return ERROR_INVALID_PARAMETER;
1704 r = msi_table_find_row(tv, rec, &new_row);
1705 if (r != ERROR_SUCCESS)
1707 ERR("can't find row to modify\n");
1708 return ERROR_FUNCTION_FAILED;
1711 /* the row cannot be changed */
1712 if (row != new_row + 1)
1713 return ERROR_FUNCTION_FAILED;
1715 return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1718 static UINT msi_table_assign(struct tagMSIVIEW *view, MSIRECORD *rec)
1720 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1721 UINT r, row;
1723 if (!tv->table)
1724 return ERROR_INVALID_PARAMETER;
1726 r = msi_table_find_row(tv, rec, &row);
1727 if (r == ERROR_SUCCESS)
1728 return TABLE_set_row(view, row, rec, (1 << tv->num_cols) - 1);
1729 else
1730 return TABLE_insert_row( view, rec, -1, FALSE );
1733 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1735 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1736 UINT row, r;
1738 r = msi_table_find_row(tv, rec, &row);
1739 if (r != ERROR_SUCCESS)
1740 return r;
1742 return TABLE_delete_row(view, row);
1745 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1747 MSIRECORD *curr;
1748 UINT r, i, count;
1750 r = TABLE_get_row(view, row - 1, &curr);
1751 if (r != ERROR_SUCCESS)
1752 return r;
1754 count = MSI_RecordGetFieldCount(rec);
1755 for (i = 0; i < count; i++)
1756 MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1758 msiobj_release(&curr->hdr);
1759 return ERROR_SUCCESS;
1762 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1763 MSIRECORD *rec, UINT row)
1765 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1766 UINT r;
1768 TRACE("%p %d %p\n", view, eModifyMode, rec );
1770 switch (eModifyMode)
1772 case MSIMODIFY_DELETE:
1773 r = modify_delete_row( view, rec );
1774 break;
1775 case MSIMODIFY_VALIDATE_NEW:
1776 r = table_validate_new( tv, rec );
1777 break;
1779 case MSIMODIFY_INSERT:
1780 r = table_validate_new( tv, rec );
1781 if (r != ERROR_SUCCESS)
1782 break;
1783 r = TABLE_insert_row( view, rec, -1, FALSE );
1784 break;
1786 case MSIMODIFY_INSERT_TEMPORARY:
1787 r = table_validate_new( tv, rec );
1788 if (r != ERROR_SUCCESS)
1789 break;
1790 r = TABLE_insert_row( view, rec, -1, TRUE );
1791 break;
1793 case MSIMODIFY_REFRESH:
1794 r = msi_refresh_record( view, rec, row );
1795 break;
1797 case MSIMODIFY_UPDATE:
1798 r = msi_table_update( view, rec, row );
1799 break;
1801 case MSIMODIFY_ASSIGN:
1802 r = msi_table_assign( view, rec );
1803 break;
1805 case MSIMODIFY_REPLACE:
1806 case MSIMODIFY_MERGE:
1807 case MSIMODIFY_VALIDATE:
1808 case MSIMODIFY_VALIDATE_FIELD:
1809 case MSIMODIFY_VALIDATE_DELETE:
1810 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1811 r = ERROR_CALL_NOT_IMPLEMENTED;
1812 break;
1814 default:
1815 r = ERROR_INVALID_DATA;
1818 return r;
1821 static UINT TABLE_delete( struct tagMSIVIEW *view )
1823 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1825 TRACE("%p\n", view );
1827 tv->table = NULL;
1828 tv->columns = NULL;
1830 if (tv->order)
1832 msi_free( tv->order->reorder );
1833 msi_free( tv->order );
1834 tv->order = NULL;
1837 msi_free( tv );
1839 return ERROR_SUCCESS;
1842 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1843 UINT val, UINT *row, MSIITERHANDLE *handle )
1845 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1846 const MSICOLUMNHASHENTRY *entry;
1848 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1850 if( !tv->table )
1851 return ERROR_INVALID_PARAMETER;
1853 if( (col==0) || (col > tv->num_cols) )
1854 return ERROR_INVALID_PARAMETER;
1856 if( !tv->columns[col-1].hash_table )
1858 UINT i;
1859 UINT num_rows = tv->table->row_count;
1860 MSICOLUMNHASHENTRY **hash_table;
1861 MSICOLUMNHASHENTRY *new_entry;
1863 if( tv->columns[col-1].offset >= tv->row_size )
1865 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1866 ERR("%p %p\n", tv, tv->columns );
1867 return ERROR_FUNCTION_FAILED;
1870 /* allocate contiguous memory for the table and its entries so we
1871 * don't have to do an expensive cleanup */
1872 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1873 num_rows * sizeof(MSICOLUMNHASHENTRY));
1874 if (!hash_table)
1875 return ERROR_OUTOFMEMORY;
1877 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1878 tv->columns[col-1].hash_table = hash_table;
1880 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1882 for (i = 0; i < num_rows; i++, new_entry++)
1884 UINT row_value;
1886 if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1887 continue;
1889 new_entry->next = NULL;
1890 new_entry->value = row_value;
1891 new_entry->row = i;
1892 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1894 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1895 while (prev_entry->next)
1896 prev_entry = prev_entry->next;
1897 prev_entry->next = new_entry;
1899 else
1900 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1904 if( !*handle )
1905 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1906 else
1907 entry = (*handle)->next;
1909 while (entry && entry->value != val)
1910 entry = entry->next;
1912 *handle = entry;
1913 if (!entry)
1914 return ERROR_NO_MORE_ITEMS;
1916 *row = entry->row;
1918 return ERROR_SUCCESS;
1921 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1923 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1924 UINT i;
1926 TRACE("%p %d\n", view, tv->table->ref_count);
1928 for (i = 0; i < tv->table->col_count; i++)
1930 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1931 InterlockedIncrement(&tv->table->colinfo[i].ref_count);
1934 return InterlockedIncrement(&tv->table->ref_count);
1937 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
1939 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1940 MSIRECORD *rec = NULL;
1941 MSIVIEW *columns = NULL;
1942 UINT row, r;
1944 rec = MSI_CreateRecord(2);
1945 if (!rec)
1946 return ERROR_OUTOFMEMORY;
1948 MSI_RecordSetStringW(rec, 1, table);
1949 MSI_RecordSetInteger(rec, 2, number);
1951 r = TABLE_CreateView(tv->db, szColumns, &columns);
1952 if (r != ERROR_SUCCESS)
1953 return r;
1955 r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row);
1956 if (r != ERROR_SUCCESS)
1957 goto done;
1959 r = TABLE_delete_row(columns, row);
1960 if (r != ERROR_SUCCESS)
1961 goto done;
1963 msi_update_table_columns(tv->db, table);
1965 done:
1966 msiobj_release(&rec->hdr);
1967 columns->ops->delete(columns);
1968 return r;
1971 static UINT TABLE_release(struct tagMSIVIEW *view)
1973 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1974 INT ref = tv->table->ref_count;
1975 UINT i, r;
1977 TRACE("%p %d\n", view, ref);
1979 for (i = 0; i < tv->table->col_count; i++)
1981 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1983 ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
1984 if (ref == 0)
1986 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
1987 tv->table->colinfo[i].number);
1988 if (r != ERROR_SUCCESS)
1989 break;
1994 ref = InterlockedDecrement(&tv->table->ref_count);
1995 if (ref == 0)
1997 if (!tv->table->row_count)
1999 list_remove(&tv->table->entry);
2000 free_table(tv->table);
2001 TABLE_delete(view);
2005 return ref;
2008 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
2009 LPCWSTR column, UINT type, BOOL hold)
2011 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2012 MSITABLE *msitable;
2013 MSIRECORD *rec;
2014 UINT r, i;
2016 rec = MSI_CreateRecord(4);
2017 if (!rec)
2018 return ERROR_OUTOFMEMORY;
2020 MSI_RecordSetStringW(rec, 1, table);
2021 MSI_RecordSetInteger(rec, 2, number);
2022 MSI_RecordSetStringW(rec, 3, column);
2023 MSI_RecordSetInteger(rec, 4, type);
2025 r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
2026 if (r != ERROR_SUCCESS)
2027 goto done;
2029 msi_update_table_columns(tv->db, table);
2031 if (!hold)
2032 goto done;
2034 msitable = find_cached_table(tv->db, table);
2035 for (i = 0; i < msitable->col_count; i++)
2037 if (!lstrcmpW(msitable->colinfo[i].colname, column))
2039 InterlockedIncrement(&msitable->colinfo[i].ref_count);
2040 break;
2044 done:
2045 msiobj_release(&rec->hdr);
2046 return r;
2049 static UINT order_add_column(struct tagMSIVIEW *view, MSIORDERINFO *order, LPCWSTR name)
2051 UINT n, r, count;
2053 r = TABLE_get_dimensions(view, NULL, &count);
2054 if (r != ERROR_SUCCESS)
2055 return r;
2057 if (order->num_cols >= count)
2058 return ERROR_FUNCTION_FAILED;
2060 r = VIEW_find_column(view, name, &n);
2061 if (r != ERROR_SUCCESS)
2062 return r;
2064 order->cols[order->num_cols] = n;
2065 TRACE("Ordering by column %s (%d)\n", debugstr_w(name), n);
2067 order->num_cols++;
2069 return ERROR_SUCCESS;
2072 static UINT order_compare(struct tagMSIVIEW *view, MSIORDERINFO *order,
2073 UINT a, UINT b, UINT *swap)
2075 UINT r, i, a_val = 0, b_val = 0;
2077 *swap = 0;
2078 for (i = 0; i < order->num_cols; i++)
2080 r = TABLE_fetch_int(view, a, order->cols[i], &a_val);
2081 if (r != ERROR_SUCCESS)
2082 return r;
2084 r = TABLE_fetch_int(view, b, order->cols[i], &b_val);
2085 if (r != ERROR_SUCCESS)
2086 return r;
2088 if (a_val != b_val)
2090 if (a_val > b_val)
2091 *swap = 1;
2092 break;
2096 return ERROR_SUCCESS;
2099 static UINT order_mergesort(struct tagMSIVIEW *view, MSIORDERINFO *order,
2100 UINT left, UINT right)
2102 UINT r, i, j, temp;
2103 UINT swap = 0, center = (left + right) / 2;
2104 UINT *array = order->reorder;
2106 if (left == right)
2107 return ERROR_SUCCESS;
2109 /* sort the left half */
2110 r = order_mergesort(view, order, left, center);
2111 if (r != ERROR_SUCCESS)
2112 return r;
2114 /* sort the right half */
2115 r = order_mergesort(view, order, center + 1, right);
2116 if (r != ERROR_SUCCESS)
2117 return r;
2119 for (i = left, j = center + 1; (i <= center) && (j <= right); i++)
2121 r = order_compare(view, order, array[i], array[j], &swap);
2122 if (r != ERROR_SUCCESS)
2123 return r;
2125 if (swap)
2127 temp = array[j];
2128 memmove(&array[i + 1], &array[i], (j - i) * sizeof(UINT));
2129 array[i] = temp;
2130 j++;
2131 center++;
2135 return ERROR_SUCCESS;
2138 static UINT order_verify(struct tagMSIVIEW *view, MSIORDERINFO *order, UINT num_rows)
2140 UINT i, swap, r;
2142 for (i = 1; i < num_rows; i++)
2144 r = order_compare(view, order, order->reorder[i - 1],
2145 order->reorder[i], &swap);
2146 if (r != ERROR_SUCCESS)
2147 return r;
2149 if (!swap)
2150 continue;
2152 ERR("Bad order! %d\n", i);
2153 return ERROR_FUNCTION_FAILED;
2156 return ERROR_SUCCESS;
2159 static UINT TABLE_sort(struct tagMSIVIEW *view, column_info *columns)
2161 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
2162 MSIORDERINFO *order;
2163 column_info *ptr;
2164 UINT r, i;
2165 UINT rows, cols;
2167 TRACE("sorting table %s\n", debugstr_w(tv->name));
2169 r = TABLE_get_dimensions(view, &rows, &cols);
2170 if (r != ERROR_SUCCESS)
2171 return r;
2173 if (rows == 0)
2174 return ERROR_SUCCESS;
2176 order = msi_alloc_zero(sizeof(MSIORDERINFO) + sizeof(UINT) * cols);
2177 if (!order)
2178 return ERROR_OUTOFMEMORY;
2180 for (ptr = columns; ptr; ptr = ptr->next)
2181 order_add_column(view, order, ptr->column);
2183 order->reorder = msi_alloc(rows * sizeof(UINT));
2184 if (!order->reorder)
2185 return ERROR_OUTOFMEMORY;
2187 for (i = 0; i < rows; i++)
2188 order->reorder[i] = i;
2190 r = order_mergesort(view, order, 0, rows - 1);
2191 if (r != ERROR_SUCCESS)
2192 return r;
2194 r = order_verify(view, order, rows);
2195 if (r != ERROR_SUCCESS)
2196 return r;
2198 tv->order = order;
2200 return ERROR_SUCCESS;
2203 static UINT TABLE_drop(struct tagMSIVIEW *view)
2205 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2206 MSIVIEW *tables = NULL;
2207 MSIRECORD *rec = NULL;
2208 UINT r, row;
2209 INT i;
2211 TRACE("dropping table %s\n", debugstr_w(tv->name));
2213 for (i = tv->table->col_count - 1; i >= 0; i--)
2215 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2216 tv->table->colinfo[i].number);
2217 if (r != ERROR_SUCCESS)
2218 return r;
2221 rec = MSI_CreateRecord(1);
2222 if (!rec)
2223 return ERROR_OUTOFMEMORY;
2225 MSI_RecordSetStringW(rec, 1, tv->name);
2227 r = TABLE_CreateView(tv->db, szTables, &tables);
2228 if (r != ERROR_SUCCESS)
2229 return r;
2231 r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row);
2232 if (r != ERROR_SUCCESS)
2233 goto done;
2235 r = TABLE_delete_row(tables, row);
2236 if (r != ERROR_SUCCESS)
2237 goto done;
2239 list_remove(&tv->table->entry);
2240 free_table(tv->table);
2241 TABLE_delete(view);
2243 done:
2244 msiobj_release(&rec->hdr);
2245 tables->ops->delete(tables);
2247 return r;
2250 static const MSIVIEWOPS table_ops =
2252 TABLE_fetch_int,
2253 TABLE_fetch_stream,
2254 TABLE_get_row,
2255 TABLE_set_row,
2256 TABLE_insert_row,
2257 TABLE_delete_row,
2258 TABLE_execute,
2259 TABLE_close,
2260 TABLE_get_dimensions,
2261 TABLE_get_column_info,
2262 TABLE_modify,
2263 TABLE_delete,
2264 TABLE_find_matching_rows,
2265 TABLE_add_ref,
2266 TABLE_release,
2267 TABLE_add_column,
2268 TABLE_remove_column,
2269 TABLE_sort,
2270 TABLE_drop,
2273 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2275 MSITABLEVIEW *tv ;
2276 UINT r, sz;
2278 static const WCHAR Streams[] = {'_','S','t','r','e','a','m','s',0};
2279 static const WCHAR Storages[] = {'_','S','t','o','r','a','g','e','s',0};
2281 TRACE("%p %s %p\n", db, debugstr_w(name), view );
2283 if ( !lstrcmpW( name, Streams ) )
2284 return STREAMS_CreateView( db, view );
2285 else if ( !lstrcmpW( name, Storages ) )
2286 return STORAGES_CreateView( db, view );
2288 sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
2289 tv = msi_alloc_zero( sz );
2290 if( !tv )
2291 return ERROR_FUNCTION_FAILED;
2293 r = get_table( db, name, &tv->table );
2294 if( r != ERROR_SUCCESS )
2296 msi_free( tv );
2297 WARN("table not found\n");
2298 return r;
2301 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2303 /* fill the structure */
2304 tv->view.ops = &table_ops;
2305 tv->db = db;
2306 tv->columns = tv->table->colinfo;
2307 tv->num_cols = tv->table->col_count;
2308 tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count );
2310 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2312 *view = (MSIVIEW*) tv;
2313 lstrcpyW( tv->name, name );
2315 return ERROR_SUCCESS;
2318 UINT MSI_CommitTables( MSIDATABASE *db )
2320 UINT r;
2321 MSITABLE *table = NULL;
2323 TRACE("%p\n",db);
2325 r = msi_save_string_table( db->strings, db->storage );
2326 if( r != ERROR_SUCCESS )
2328 WARN("failed to save string table r=%08x\n",r);
2329 return r;
2332 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2334 r = save_table( db, table );
2335 if( r != ERROR_SUCCESS )
2337 WARN("failed to save table %s (r=%08x)\n",
2338 debugstr_w(table->name), r);
2339 return r;
2343 /* force everything to reload next time */
2344 free_cached_tables( db );
2346 return ERROR_SUCCESS;
2349 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2351 MSITABLE *t;
2352 UINT r;
2354 TRACE("%p %s\n", db, debugstr_w(table));
2356 if (!table)
2357 return MSICONDITION_ERROR;
2359 r = get_table( db, table, &t );
2360 if (r != ERROR_SUCCESS)
2361 return MSICONDITION_NONE;
2363 return t->persistent;
2366 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2368 UINT ret = 0, i;
2370 for (i = 0; i < bytes; i++)
2371 ret += (data[col + i] << i * 8);
2373 return ret;
2376 static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
2378 LPWSTR stname = NULL, sval, p;
2379 DWORD len;
2380 UINT i, r;
2382 TRACE("%p %p\n", tv, rec);
2384 len = lstrlenW( tv->name ) + 1;
2385 stname = msi_alloc( len*sizeof(WCHAR) );
2386 if ( !stname )
2388 r = ERROR_OUTOFMEMORY;
2389 goto err;
2392 lstrcpyW( stname, tv->name );
2394 for ( i = 0; i < tv->num_cols; i++ )
2396 if ( tv->columns[i].type & MSITYPE_KEY )
2398 sval = msi_dup_record_field( rec, i + 1 );
2399 if ( !sval )
2401 r = ERROR_OUTOFMEMORY;
2402 goto err;
2405 len += lstrlenW( szDot ) + lstrlenW ( sval );
2406 p = msi_realloc ( stname, len*sizeof(WCHAR) );
2407 if ( !p )
2409 r = ERROR_OUTOFMEMORY;
2410 goto err;
2412 stname = p;
2414 lstrcatW( stname, szDot );
2415 lstrcatW( stname, sval );
2417 msi_free( sval );
2419 else
2420 continue;
2423 *pstname = encode_streamname( FALSE, stname );
2424 msi_free( stname );
2426 return ERROR_SUCCESS;
2428 err:
2429 msi_free ( stname );
2430 *pstname = NULL;
2431 return r;
2434 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2435 IStorage *stg,
2436 const BYTE *rawdata, UINT bytes_per_strref )
2438 UINT i, val, ofs = 0;
2439 USHORT mask;
2440 MSICOLUMNINFO *columns = tv->columns;
2441 MSIRECORD *rec;
2443 mask = rawdata[0] | (rawdata[1] << 8);
2444 rawdata += 2;
2446 rec = MSI_CreateRecord( tv->num_cols );
2447 if( !rec )
2448 return rec;
2450 TRACE("row ->\n");
2451 for( i=0; i<tv->num_cols; i++ )
2453 if ( (mask&1) && (i>=(mask>>8)) )
2454 break;
2455 /* all keys must be present */
2456 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2457 continue;
2459 if( MSITYPE_IS_BINARY(tv->columns[i].type) )
2461 LPWSTR encname;
2462 IStream *stm = NULL;
2463 UINT r;
2465 ofs += bytes_per_column( tv->db, &columns[i] );
2467 r = msi_record_encoded_stream_name( tv, rec, &encname );
2468 if ( r != ERROR_SUCCESS )
2469 return NULL;
2471 r = IStorage_OpenStream( stg, encname, NULL,
2472 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
2473 msi_free( encname );
2474 if ( r != ERROR_SUCCESS )
2475 return NULL;
2477 MSI_RecordSetStream( rec, i+1, stm );
2478 TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
2480 else if( columns[i].type & MSITYPE_STRING )
2482 LPCWSTR sval;
2484 val = read_raw_int(rawdata, ofs, bytes_per_strref);
2485 sval = msi_string_lookup_id( st, val );
2486 MSI_RecordSetStringW( rec, i+1, sval );
2487 TRACE(" field %d [%s]\n", i+1, debugstr_w(sval));
2488 ofs += bytes_per_strref;
2490 else
2492 UINT n = bytes_per_column( tv->db, &columns[i] );
2493 switch( n )
2495 case 2:
2496 val = read_raw_int(rawdata, ofs, n);
2497 if (val)
2498 MSI_RecordSetInteger( rec, i+1, val^0x8000 );
2499 TRACE(" field %d [0x%04x]\n", i+1, val );
2500 break;
2501 case 4:
2502 val = read_raw_int(rawdata, ofs, n);
2503 if (val)
2504 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2505 TRACE(" field %d [0x%08x]\n", i+1, val );
2506 break;
2507 default:
2508 ERR("oops - unknown column width %d\n", n);
2509 break;
2511 ofs += n;
2514 return rec;
2517 static void dump_record( MSIRECORD *rec )
2519 UINT i, n;
2521 n = MSI_RecordGetFieldCount( rec );
2522 for( i=1; i<=n; i++ )
2524 LPCWSTR sval = MSI_RecordGetString( rec, i );
2526 if( MSI_RecordIsNull( rec, i ) )
2527 TRACE("row -> []\n");
2528 else if( (sval = MSI_RecordGetString( rec, i )) )
2529 TRACE("row -> [%s]\n", debugstr_w(sval));
2530 else
2531 TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2535 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2537 LPCWSTR sval;
2538 UINT i;
2540 for( i=0; i<(rawsize/2); i++ )
2542 sval = msi_string_lookup_id( st, rawdata[i] );
2543 MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
2547 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2549 LPCWSTR str;
2550 UINT i, r, *data;
2552 data = msi_alloc( tv->num_cols *sizeof (UINT) );
2553 for( i=0; i<tv->num_cols; i++ )
2555 data[i] = 0;
2557 if ( ~tv->columns[i].type & MSITYPE_KEY )
2558 continue;
2560 /* turn the transform column value into a row value */
2561 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2562 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2564 str = MSI_RecordGetString( rec, i+1 );
2565 r = msi_string2idW( tv->db->strings, str, &data[i] );
2567 /* if there's no matching string in the string table,
2568 these keys can't match any record, so fail now. */
2569 if( ERROR_SUCCESS != r )
2571 msi_free( data );
2572 return NULL;
2575 else
2577 data[i] = MSI_RecordGetInteger( rec, i+1 );
2579 if (data[i] == MSI_NULL_INTEGER)
2580 data[i] = 0;
2581 else if ((tv->columns[i].type&0xff) == 2)
2582 data[i] += 0x8000;
2583 else
2584 data[i] += 0x80000000;
2587 return data;
2590 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data )
2592 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2594 for( i=0; i<tv->num_cols; i++ )
2596 if ( ~tv->columns[i].type & MSITYPE_KEY )
2597 continue;
2599 /* turn the transform column value into a row value */
2600 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2601 if ( r != ERROR_SUCCESS )
2603 ERR("TABLE_fetch_int shouldn't fail here\n");
2604 break;
2607 /* if this key matches, move to the next column */
2608 if ( x != data[i] )
2610 ret = ERROR_FUNCTION_FAILED;
2611 break;
2614 ret = ERROR_SUCCESS;
2617 return ret;
2620 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row )
2622 UINT i, r = ERROR_FUNCTION_FAILED, *data;
2624 data = msi_record_to_row( tv, rec );
2625 if( !data )
2626 return r;
2627 for( i = 0; i < tv->table->row_count; i++ )
2629 r = msi_row_matches( tv, i, data );
2630 if( r == ERROR_SUCCESS )
2632 *row = i;
2633 break;
2636 msi_free( data );
2637 return r;
2640 typedef struct
2642 struct list entry;
2643 LPWSTR name;
2644 } TRANSFORMDATA;
2646 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2647 string_table *st, TRANSFORMDATA *transform,
2648 UINT bytes_per_strref )
2650 UINT rawsize = 0;
2651 BYTE *rawdata = NULL;
2652 MSITABLEVIEW *tv = NULL;
2653 UINT r, n, sz, i, mask;
2654 MSIRECORD *rec = NULL;
2655 UINT colcol = 0;
2656 WCHAR coltable[32];
2657 LPWSTR name;
2659 if (!transform)
2660 return ERROR_SUCCESS;
2662 name = transform->name;
2664 coltable[0] = 0;
2665 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2667 /* read the transform data */
2668 read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2669 if ( !rawdata )
2671 TRACE("table %s empty\n", debugstr_w(name) );
2672 return ERROR_INVALID_TABLE;
2675 /* create a table view */
2676 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2677 if( r != ERROR_SUCCESS )
2678 goto err;
2680 r = tv->view.ops->execute( &tv->view, NULL );
2681 if( r != ERROR_SUCCESS )
2682 goto err;
2684 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2685 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2687 /* interpret the data */
2688 r = ERROR_SUCCESS;
2689 for( n=0; n < rawsize; )
2691 mask = rawdata[n] | (rawdata[n+1] << 8);
2693 if (mask&1)
2696 * if the low bit is set, columns are continuous and
2697 * the number of columns is specified in the high byte
2699 sz = 2;
2700 for( i=0; i<tv->num_cols; i++ )
2702 if( (tv->columns[i].type & MSITYPE_STRING) &&
2703 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2704 sz += bytes_per_strref;
2705 else
2706 sz += bytes_per_column( tv->db, &tv->columns[i] );
2709 else
2712 * If the low bit is not set, mask is a bitmask.
2713 * Excepting for key fields, which are always present,
2714 * each bit indicates that a field is present in the transform record.
2716 * mask == 0 is a special case ... only the keys will be present
2717 * and it means that this row should be deleted.
2719 sz = 2;
2720 for( i=0; i<tv->num_cols; i++ )
2722 if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
2724 if( (tv->columns[i].type & MSITYPE_STRING) &&
2725 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2726 sz += bytes_per_strref;
2727 else
2728 sz += bytes_per_column( tv->db, &tv->columns[i] );
2733 /* check we didn't run of the end of the table */
2734 if ( (n+sz) > rawsize )
2736 ERR("borked.\n");
2737 dump_table( st, (USHORT *)rawdata, rawsize );
2738 break;
2741 rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2742 if (rec)
2744 if ( mask & 1 )
2746 WCHAR table[32];
2747 DWORD sz = 32;
2748 UINT number = MSI_NULL_INTEGER;
2750 TRACE("inserting record\n");
2752 if (!lstrcmpW(name, szColumns))
2754 MSI_RecordGetStringW( rec, 1, table, &sz );
2755 number = MSI_RecordGetInteger( rec, 2 );
2758 * Native msi seems writes nul into the Number (2nd) column of
2759 * the _Columns table, only when the columns are from a new table
2761 if ( number == MSI_NULL_INTEGER )
2763 /* reset the column number on a new table */
2764 if ( lstrcmpW(coltable, table) )
2766 colcol = 0;
2767 lstrcpyW( coltable, table );
2770 /* fix nul column numbers */
2771 MSI_RecordSetInteger( rec, 2, ++colcol );
2775 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2776 if (r != ERROR_SUCCESS)
2777 WARN("insert row failed\n");
2779 if ( number != MSI_NULL_INTEGER && !lstrcmpW(name, szColumns) )
2780 msi_update_table_columns( db, table );
2782 else
2784 UINT row = 0;
2786 r = msi_table_find_row( tv, rec, &row );
2787 if (r != ERROR_SUCCESS)
2788 WARN("no matching row to transform\n");
2789 else if ( mask )
2791 TRACE("modifying row [%d]:\n", row);
2792 TABLE_set_row( &tv->view, row, rec, mask );
2794 else
2796 TRACE("deleting row [%d]:\n", row);
2797 TABLE_delete_row( &tv->view, row );
2800 if( TRACE_ON(msidb) ) dump_record( rec );
2801 msiobj_release( &rec->hdr );
2804 n += sz;
2807 err:
2808 /* no need to free the table, it's associated with the database */
2809 msi_free( rawdata );
2810 if( tv )
2811 tv->view.ops->delete( &tv->view );
2813 return ERROR_SUCCESS;
2817 * msi_table_apply_transform
2819 * Enumerate the table transforms in a transform storage and apply each one.
2821 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2823 struct list transforms;
2824 IEnumSTATSTG *stgenum = NULL;
2825 TRANSFORMDATA *transform;
2826 TRANSFORMDATA *tables = NULL, *columns = NULL;
2827 HRESULT r;
2828 STATSTG stat;
2829 string_table *strings;
2830 UINT ret = ERROR_FUNCTION_FAILED;
2831 UINT bytes_per_strref;
2833 TRACE("%p %p\n", db, stg );
2835 strings = msi_load_string_table( stg, &bytes_per_strref );
2836 if( !strings )
2837 goto end;
2839 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2840 if( FAILED( r ) )
2841 goto end;
2843 list_init(&transforms);
2845 while ( TRUE )
2847 MSITABLEVIEW *tv = NULL;
2848 WCHAR name[0x40];
2849 ULONG count = 0;
2851 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2852 if ( FAILED( r ) || !count )
2853 break;
2855 decode_streamname( stat.pwcsName, name );
2856 CoTaskMemFree( stat.pwcsName );
2857 if ( name[0] != 0x4840 )
2858 continue;
2860 if ( !lstrcmpW( name+1, szStringPool ) ||
2861 !lstrcmpW( name+1, szStringData ) )
2862 continue;
2864 transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2865 if ( !transform )
2866 break;
2868 list_add_tail( &transforms, &transform->entry );
2870 transform->name = strdupW( name + 1 );
2872 if ( !lstrcmpW( transform->name, szTables ) )
2873 tables = transform;
2874 else if (!lstrcmpW( transform->name, szColumns ) )
2875 columns = transform;
2877 TRACE("transform contains stream %s\n", debugstr_w(name));
2879 /* load the table */
2880 r = TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv );
2881 if( r != ERROR_SUCCESS )
2882 continue;
2884 r = tv->view.ops->execute( &tv->view, NULL );
2885 if( r != ERROR_SUCCESS )
2887 tv->view.ops->delete( &tv->view );
2888 continue;
2891 tv->view.ops->delete( &tv->view );
2895 * Apply _Tables and _Columns transforms first so that
2896 * the table metadata is correct, and empty tables exist.
2898 ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2899 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2900 goto end;
2902 ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2903 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2904 goto end;
2906 ret = ERROR_SUCCESS;
2908 while ( !list_empty( &transforms ) )
2910 transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2912 if ( lstrcmpW( transform->name, szColumns ) &&
2913 lstrcmpW( transform->name, szTables ) &&
2914 ret == ERROR_SUCCESS )
2916 ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
2919 list_remove( &transform->entry );
2920 msi_free( transform->name );
2921 msi_free( transform );
2924 if ( ret == ERROR_SUCCESS )
2925 append_storage_to_db( db, stg );
2927 end:
2928 if ( stgenum )
2929 IEnumSTATSTG_Release( stgenum );
2930 if ( strings )
2931 msi_destroy_stringtable( strings );
2933 return ret;
2936 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
2938 MSITRANSFORM *t;
2940 t = msi_alloc( sizeof *t );
2941 t->stg = stg;
2942 IStorage_AddRef( stg );
2943 list_add_tail( &db->transforms, &t->entry );
2946 void msi_free_transforms( MSIDATABASE *db )
2948 while( !list_empty( &db->transforms ) )
2950 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
2951 MSITRANSFORM, entry );
2952 list_remove( &t->entry );
2953 IStorage_Release( t->stg );
2954 msi_free( t );
2958 static UINT table_find_insert_idx (MSIVIEW *view, LPCWSTR name, INT *pidx)
2960 UINT r, name_id, row_id;
2961 INT idx;
2962 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
2964 TRACE ("%p %s\n", view, debugstr_w(name));
2966 r = msi_string2idW(tv->db->strings, name, &name_id);
2967 if (r != ERROR_SUCCESS)
2969 *pidx = -1;
2970 return r;
2973 for( idx = 0; idx < tv->table->row_count; idx++ )
2975 r = TABLE_fetch_int( &tv->view, idx, 1, &row_id );
2976 if (row_id > name_id)
2977 break;
2980 *pidx = idx;
2981 return ERROR_SUCCESS;