shell32: Remove superflous NULL check (Coverity).
[wine/multimedia.git] / dlls / msi / table.c
blobecca7c9bd1631591ad7495ccd2aa2648a5b64682
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
46 typedef struct tagMSICOLUMNHASHENTRY
48 struct tagMSICOLUMNHASHENTRY *next;
49 UINT value;
50 UINT row;
51 } MSICOLUMNHASHENTRY;
53 typedef struct tagMSICOLUMNINFO
55 LPWSTR tablename;
56 UINT number;
57 LPWSTR colname;
58 UINT type;
59 UINT offset;
60 INT ref_count;
61 BOOL temporary;
62 MSICOLUMNHASHENTRY **hash_table;
63 } MSICOLUMNINFO;
65 typedef struct tagMSIORDERINFO
67 UINT *reorder;
68 UINT num_cols;
69 UINT cols[1];
70 } MSIORDERINFO;
72 struct tagMSITABLE
74 BYTE **data;
75 BOOL *data_persistent;
76 UINT row_count;
77 struct list entry;
78 MSICOLUMNINFO *colinfo;
79 UINT col_count;
80 MSICONDITION persistent;
81 INT ref_count;
82 WCHAR name[1];
85 /* information for default tables */
86 static WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
87 static WCHAR szTable[] = { 'T','a','b','l','e',0 };
88 static WCHAR szName[] = { 'N','a','m','e',0 };
89 static WCHAR szColumns[] = { '_','C','o','l','u','m','n','s',0 };
90 static WCHAR szNumber[] = { 'N','u','m','b','e','r',0 };
91 static WCHAR szType[] = { 'T','y','p','e',0 };
93 static const MSICOLUMNINFO _Columns_cols[4] = {
94 { szColumns, 1, szTable, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
95 { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2, 2, 0, 0, NULL },
96 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, 0, NULL },
97 { szColumns, 4, szType, MSITYPE_VALID | 2, 6, 0, 0, NULL },
100 static const MSICOLUMNINFO _Tables_cols[1] = {
101 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
104 #define MAX_STREAM_NAME 0x1f
106 static inline UINT bytes_per_column( MSIDATABASE *db, const MSICOLUMNINFO *col, UINT bytes_per_strref )
108 if( MSITYPE_IS_BINARY(col->type) )
109 return 2;
111 if( col->type & MSITYPE_STRING )
112 return bytes_per_strref;
114 if( (col->type & 0xff) <= 2)
115 return 2;
117 if( (col->type & 0xff) != 4 )
118 ERR("Invalid column size!\n");
120 return 4;
123 static int utf2mime(int x)
125 if( (x>='0') && (x<='9') )
126 return x-'0';
127 if( (x>='A') && (x<='Z') )
128 return x-'A'+10;
129 if( (x>='a') && (x<='z') )
130 return x-'a'+10+26;
131 if( x=='.' )
132 return 10+26+26;
133 if( x=='_' )
134 return 10+26+26+1;
135 return -1;
138 LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
140 DWORD count = MAX_STREAM_NAME;
141 DWORD ch, next;
142 LPWSTR out, p;
144 if( !bTable )
145 count = lstrlenW( in )+2;
146 if (!(out = msi_alloc( count*sizeof(WCHAR) ))) return NULL;
147 p = out;
149 if( bTable )
151 *p++ = 0x4840;
152 count --;
154 while( count -- )
156 ch = *in++;
157 if( !ch )
159 *p = ch;
160 return out;
162 if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
164 ch = utf2mime(ch) + 0x4800;
165 next = *in;
166 if( next && (next<0x80) )
168 next = utf2mime(next);
169 if( next != -1 )
171 next += 0x3ffffc0;
172 ch += (next<<6);
173 in++;
177 *p++ = ch;
179 ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
180 msi_free( out );
181 return NULL;
184 static int mime2utf(int x)
186 if( x<10 )
187 return x + '0';
188 if( x<(10+26))
189 return x - 10 + 'A';
190 if( x<(10+26+26))
191 return x - 10 - 26 + 'a';
192 if( x == (10+26+26) )
193 return '.';
194 return '_';
197 BOOL decode_streamname(LPCWSTR in, LPWSTR out)
199 WCHAR ch;
200 DWORD count = 0;
202 while ( (ch = *in++) )
204 if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
206 if( ch >= 0x4800 )
207 ch = mime2utf(ch-0x4800);
208 else
210 ch -= 0x3800;
211 *out++ = mime2utf(ch&0x3f);
212 count++;
213 ch = mime2utf((ch>>6)&0x3f);
216 *out++ = ch;
217 count++;
219 *out = 0;
220 return count;
223 void enum_stream_names( IStorage *stg )
225 IEnumSTATSTG *stgenum = NULL;
226 HRESULT r;
227 STATSTG stat;
228 ULONG n, count;
229 WCHAR name[0x40];
231 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
232 if( FAILED( r ) )
233 return;
235 n = 0;
236 while( 1 )
238 count = 0;
239 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
240 if( FAILED( r ) || !count )
241 break;
242 decode_streamname( stat.pwcsName, name );
243 TRACE("stream %2d -> %s %s\n", n,
244 debugstr_w(stat.pwcsName), debugstr_w(name) );
245 CoTaskMemFree( stat.pwcsName );
246 n++;
249 IEnumSTATSTG_Release( stgenum );
252 UINT read_stream_data( IStorage *stg, LPCWSTR stname, BOOL table,
253 BYTE **pdata, UINT *psz )
255 HRESULT r;
256 UINT ret = ERROR_FUNCTION_FAILED;
257 VOID *data;
258 ULONG sz, count;
259 IStream *stm = NULL;
260 STATSTG stat;
261 LPWSTR encname;
263 encname = encode_streamname(table, stname);
265 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
267 r = IStorage_OpenStream(stg, encname, NULL,
268 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
269 msi_free( encname );
270 if( FAILED( r ) )
272 WARN("open stream failed r = %08x - empty table?\n", r);
273 return ret;
276 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
277 if( FAILED( r ) )
279 WARN("open stream failed r = %08x!\n", r);
280 goto end;
283 if( stat.cbSize.QuadPart >> 32 )
285 WARN("Too big!\n");
286 goto end;
289 sz = stat.cbSize.QuadPart;
290 data = msi_alloc( sz );
291 if( !data )
293 WARN("couldn't allocate memory r=%08x!\n", r);
294 ret = ERROR_NOT_ENOUGH_MEMORY;
295 goto end;
298 r = IStream_Read(stm, data, sz, &count );
299 if( FAILED( r ) || ( count != sz ) )
301 msi_free( data );
302 WARN("read stream failed r = %08x!\n", r);
303 goto end;
306 *pdata = data;
307 *psz = sz;
308 ret = ERROR_SUCCESS;
310 end:
311 IStream_Release( stm );
313 return ret;
316 UINT write_stream_data( IStorage *stg, LPCWSTR stname,
317 LPCVOID data, UINT sz, BOOL bTable )
319 HRESULT r;
320 UINT ret = ERROR_FUNCTION_FAILED;
321 ULONG count;
322 IStream *stm = NULL;
323 ULARGE_INTEGER size;
324 LARGE_INTEGER pos;
325 LPWSTR encname;
327 encname = encode_streamname(bTable, stname );
328 r = IStorage_OpenStream( stg, encname, NULL,
329 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
330 if( FAILED(r) )
332 r = IStorage_CreateStream( stg, encname,
333 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
335 msi_free( encname );
336 if( FAILED( r ) )
338 WARN("open stream failed r = %08x\n", r);
339 return ret;
342 size.QuadPart = sz;
343 r = IStream_SetSize( stm, size );
344 if( FAILED( r ) )
346 WARN("Failed to SetSize\n");
347 goto end;
350 pos.QuadPart = 0;
351 r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
352 if( FAILED( r ) )
354 WARN("Failed to Seek\n");
355 goto end;
358 if (sz)
360 r = IStream_Write(stm, data, sz, &count );
361 if( FAILED( r ) || ( count != sz ) )
363 WARN("Failed to Write\n");
364 goto end;
368 ret = ERROR_SUCCESS;
370 end:
371 IStream_Release( stm );
373 return ret;
376 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
378 UINT i;
380 for (i = 0; i < count; i++)
382 msi_free( colinfo[i].tablename );
383 msi_free( colinfo[i].colname );
384 msi_free( colinfo[i].hash_table );
388 static void free_table( MSITABLE *table )
390 UINT i;
391 for( i=0; i<table->row_count; i++ )
392 msi_free( table->data[i] );
393 msi_free( table->data );
394 msi_free( table->data_persistent );
395 msi_free_colinfo( table->colinfo, table->col_count );
396 msi_free( table->colinfo );
397 msi_free( table );
400 static UINT msi_table_get_row_size( MSIDATABASE *db, const MSICOLUMNINFO *cols, UINT count, UINT bytes_per_strref )
402 const MSICOLUMNINFO *last_col;
404 if (!count)
405 return 0;
407 if (bytes_per_strref != LONG_STR_BYTES)
409 UINT i, size = 0;
410 for (i = 0; i < count; i++) size += bytes_per_column( db, &cols[i], bytes_per_strref );
411 return size;
413 last_col = &cols[count - 1];
414 return last_col->offset + bytes_per_column( db, last_col, bytes_per_strref );
417 /* add this table to the list of cached tables in the database */
418 static UINT read_table_from_storage( MSIDATABASE *db, MSITABLE *t, IStorage *stg )
420 BYTE *rawdata = NULL;
421 UINT rawsize = 0, i, j, row_size, row_size_mem;
423 TRACE("%s\n",debugstr_w(t->name));
425 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, db->bytes_per_strref );
426 row_size_mem = msi_table_get_row_size( db, t->colinfo, t->col_count, LONG_STR_BYTES );
428 /* if we can't read the table, just assume that it's empty */
429 read_stream_data( stg, t->name, TRUE, &rawdata, &rawsize );
430 if( !rawdata )
431 return ERROR_SUCCESS;
433 TRACE("Read %d bytes\n", rawsize );
435 if( rawsize % row_size )
437 WARN("Table size is invalid %d/%d\n", rawsize, row_size );
438 goto err;
441 t->row_count = rawsize / row_size;
442 t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
443 if( !t->data )
444 goto err;
445 t->data_persistent = msi_alloc_zero( t->row_count * sizeof(BOOL));
446 if ( !t->data_persistent )
447 goto err;
449 /* transpose all the data */
450 TRACE("Transposing data from %d rows\n", t->row_count );
451 for (i = 0; i < t->row_count; i++)
453 UINT ofs = 0, ofs_mem = 0;
455 t->data[i] = msi_alloc( row_size_mem );
456 if( !t->data[i] )
457 goto err;
458 t->data_persistent[i] = TRUE;
460 for (j = 0; j < t->col_count; j++)
462 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
463 UINT n = bytes_per_column( db, &t->colinfo[j], db->bytes_per_strref );
464 UINT k;
466 if ( n != 2 && n != 3 && n != 4 )
468 ERR("oops - unknown column width %d\n", n);
469 goto err;
471 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
473 for (k = 0; k < m; k++)
475 if (k < n)
476 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
477 else
478 t->data[i][ofs_mem + k] = 0;
481 else
483 for (k = 0; k < n; k++)
484 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
486 ofs_mem += m;
487 ofs += n;
491 msi_free( rawdata );
492 return ERROR_SUCCESS;
493 err:
494 msi_free( rawdata );
495 return ERROR_FUNCTION_FAILED;
498 void free_cached_tables( MSIDATABASE *db )
500 while( !list_empty( &db->tables ) )
502 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
504 list_remove( &t->entry );
505 free_table( t );
509 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
511 MSITABLE *t;
513 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
514 if( !strcmpW( name, t->name ) )
515 return t;
517 return NULL;
520 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo, DWORD count )
522 DWORD i;
524 for (i = 0; colinfo && i < count; i++)
526 assert( i + 1 == colinfo[i].number );
527 if (i) colinfo[i].offset = colinfo[i - 1].offset +
528 bytes_per_column( db, &colinfo[i - 1], LONG_STR_BYTES );
529 else colinfo[i].offset = 0;
531 TRACE("column %d is [%s] with type %08x ofs %d\n",
532 colinfo[i].number, debugstr_w(colinfo[i].colname),
533 colinfo[i].type, colinfo[i].offset);
537 static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO *colinfo, UINT *sz )
539 const MSICOLUMNINFO *p;
540 DWORD i, n;
542 TRACE("%s\n", debugstr_w(name));
544 if (!strcmpW( name, szTables ))
546 p = _Tables_cols;
547 n = 1;
549 else if (!strcmpW( name, szColumns ))
551 p = _Columns_cols;
552 n = 4;
554 else return ERROR_FUNCTION_FAILED;
556 /* duplicate the string data so we can free it in msi_free_colinfo */
557 for (i = 0; i < n; i++)
559 if (colinfo && i < *sz)
561 colinfo[i] = p[i];
562 colinfo[i].tablename = strdupW( p[i].tablename );
563 colinfo[i].colname = strdupW( p[i].colname );
565 if (colinfo && i >= *sz) break;
567 table_calc_column_offsets( db, colinfo, n );
568 *sz = n;
569 return ERROR_SUCCESS;
572 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz );
574 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
576 UINT r, column_count = 0;
577 MSICOLUMNINFO *columns;
579 /* get the number of columns in this table */
580 column_count = 0;
581 r = get_tablecolumns( db, name, NULL, &column_count );
582 if (r != ERROR_SUCCESS)
583 return r;
585 *pcount = column_count;
587 /* if there's no columns, there's no table */
588 if (!column_count)
589 return ERROR_INVALID_PARAMETER;
591 TRACE("table %s found\n", debugstr_w(name));
593 columns = msi_alloc( column_count * sizeof(MSICOLUMNINFO) );
594 if (!columns)
595 return ERROR_FUNCTION_FAILED;
597 r = get_tablecolumns( db, name, columns, &column_count );
598 if (r != ERROR_SUCCESS)
600 msi_free( columns );
601 return ERROR_FUNCTION_FAILED;
603 *pcols = columns;
604 return r;
607 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
609 MSITABLE *table;
610 UINT r;
612 /* first, see if the table is cached */
613 table = find_cached_table( db, name );
614 if (table)
616 *table_ret = table;
617 return ERROR_SUCCESS;
620 /* nonexistent tables should be interpreted as empty tables */
621 table = msi_alloc( sizeof(MSITABLE) + lstrlenW( name ) * sizeof(WCHAR) );
622 if (!table)
623 return ERROR_FUNCTION_FAILED;
625 table->row_count = 0;
626 table->data = NULL;
627 table->data_persistent = NULL;
628 table->colinfo = NULL;
629 table->col_count = 0;
630 table->persistent = MSICONDITION_TRUE;
631 lstrcpyW( table->name, name );
633 if (!strcmpW( name, szTables ) || !strcmpW( name, szColumns ))
634 table->persistent = MSICONDITION_NONE;
636 r = table_get_column_info( db, name, &table->colinfo, &table->col_count );
637 if (r != ERROR_SUCCESS)
639 free_table( table );
640 return r;
642 r = read_table_from_storage( db, table, db->storage );
643 if (r != ERROR_SUCCESS)
645 free_table( table );
646 return r;
648 list_add_head( &db->tables, &table->entry );
649 *table_ret = table;
650 return ERROR_SUCCESS;
653 static UINT read_table_int( BYTE *const *data, UINT row, UINT col, UINT bytes )
655 UINT ret = 0, i;
657 for (i = 0; i < bytes; i++)
658 ret += data[row][col + i] << i * 8;
660 return ret;
663 static LPWSTR msi_makestring( const MSIDATABASE *db, UINT string_id )
665 return strdupW( msi_string_lookup_id( db->strings, string_id ) );
668 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz )
670 UINT r, i, n = 0, table_id, count, maxcount = *sz;
671 MSITABLE *table = NULL;
673 TRACE("%s\n", debugstr_w(szTableName));
675 /* first check if there is a default table with that name */
676 r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
677 if (r == ERROR_SUCCESS && *sz)
678 return r;
680 r = get_table( db, szColumns, &table );
681 if (r != ERROR_SUCCESS)
683 ERR("couldn't load _Columns table\n");
684 return ERROR_FUNCTION_FAILED;
687 /* convert table and column names to IDs from the string table */
688 r = msi_string2idW( db->strings, szTableName, &table_id );
689 if (r != ERROR_SUCCESS)
691 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
692 return r;
694 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
696 /* Note: _Columns table doesn't have non-persistent data */
698 /* if maxcount is non-zero, assume it's exactly right for this table */
699 memset( colinfo, 0, maxcount * sizeof(*colinfo) );
700 count = table->row_count;
701 for (i = 0; i < count; i++)
703 if (read_table_int( table->data, i, 0, LONG_STR_BYTES) != table_id) continue;
704 if (colinfo)
706 UINT id = read_table_int( table->data, i, table->colinfo[2].offset, LONG_STR_BYTES );
707 UINT col = read_table_int( table->data, i, table->colinfo[1].offset, sizeof(USHORT) ) - (1 << 15);
709 /* check the column number is in range */
710 if (col < 1 || col > maxcount)
712 ERR("column %d out of range\n", col);
713 continue;
715 /* check if this column was already set */
716 if (colinfo[col - 1].number)
718 ERR("duplicate column %d\n", col);
719 continue;
721 colinfo[col - 1].tablename = msi_makestring( db, table_id );
722 colinfo[col - 1].number = col;
723 colinfo[col - 1].colname = msi_makestring( db, id );
724 colinfo[col - 1].type = read_table_int( table->data, i, table->colinfo[3].offset,
725 sizeof(USHORT) ) - (1 << 15);
726 colinfo[col - 1].offset = 0;
727 colinfo[col - 1].ref_count = 0;
728 colinfo[col - 1].hash_table = NULL;
730 n++;
732 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
734 if (colinfo && n != maxcount)
736 ERR("missing column in table %s\n", debugstr_w(szTableName));
737 msi_free_colinfo( colinfo, maxcount );
738 return ERROR_FUNCTION_FAILED;
740 table_calc_column_offsets( db, colinfo, n );
741 *sz = n;
742 return ERROR_SUCCESS;
745 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
746 MSICONDITION persistent, MSITABLE **table_ret)
748 UINT r, nField;
749 MSIVIEW *tv = NULL;
750 MSIRECORD *rec = NULL;
751 column_info *col;
752 MSITABLE *table;
753 UINT i;
755 /* only add tables that don't exist already */
756 if( TABLE_Exists(db, name ) )
758 WARN("table %s exists\n", debugstr_w(name));
759 return ERROR_BAD_QUERY_SYNTAX;
762 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
763 if( !table )
764 return ERROR_FUNCTION_FAILED;
766 table->ref_count = 1;
767 table->row_count = 0;
768 table->data = NULL;
769 table->data_persistent = NULL;
770 table->colinfo = NULL;
771 table->col_count = 0;
772 table->persistent = persistent;
773 lstrcpyW( table->name, name );
775 for( col = col_info; col; col = col->next )
776 table->col_count++;
778 table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
779 if (!table->colinfo)
781 free_table( table );
782 return ERROR_FUNCTION_FAILED;
785 for( i = 0, col = col_info; col; i++, col = col->next )
787 table->colinfo[ i ].tablename = strdupW( col->table );
788 table->colinfo[ i ].number = i + 1;
789 table->colinfo[ i ].colname = strdupW( col->column );
790 table->colinfo[ i ].type = col->type;
791 table->colinfo[ i ].offset = 0;
792 table->colinfo[ i ].ref_count = 0;
793 table->colinfo[ i ].hash_table = NULL;
794 table->colinfo[ i ].temporary = col->temporary;
796 table_calc_column_offsets( db, table->colinfo, table->col_count);
798 r = TABLE_CreateView( db, szTables, &tv );
799 TRACE("CreateView returned %x\n", r);
800 if( r )
802 free_table( table );
803 return r;
806 r = tv->ops->execute( tv, 0 );
807 TRACE("tv execute returned %x\n", r);
808 if( r )
809 goto err;
811 rec = MSI_CreateRecord( 1 );
812 if( !rec )
813 goto err;
815 r = MSI_RecordSetStringW( rec, 1, name );
816 if( r )
817 goto err;
819 r = tv->ops->insert_row( tv, rec, -1, persistent == MSICONDITION_FALSE );
820 TRACE("insert_row returned %x\n", r);
821 if( r )
822 goto err;
824 tv->ops->delete( tv );
825 tv = NULL;
827 msiobj_release( &rec->hdr );
828 rec = NULL;
830 if( persistent != MSICONDITION_FALSE )
832 /* add each column to the _Columns table */
833 r = TABLE_CreateView( db, szColumns, &tv );
834 if( r )
835 return r;
837 r = tv->ops->execute( tv, 0 );
838 TRACE("tv execute returned %x\n", r);
839 if( r )
840 goto err;
842 rec = MSI_CreateRecord( 4 );
843 if( !rec )
844 goto err;
846 r = MSI_RecordSetStringW( rec, 1, name );
847 if( r )
848 goto err;
851 * need to set the table, column number, col name and type
852 * for each column we enter in the table
854 nField = 1;
855 for( col = col_info; col; col = col->next )
857 r = MSI_RecordSetInteger( rec, 2, nField );
858 if( r )
859 goto err;
861 r = MSI_RecordSetStringW( rec, 3, col->column );
862 if( r )
863 goto err;
865 r = MSI_RecordSetInteger( rec, 4, col->type );
866 if( r )
867 goto err;
869 r = tv->ops->insert_row( tv, rec, -1, FALSE );
870 if( r )
871 goto err;
873 nField++;
875 if( !col )
876 r = ERROR_SUCCESS;
879 err:
880 if (rec)
881 msiobj_release( &rec->hdr );
882 /* FIXME: remove values from the string table on error */
883 if( tv )
884 tv->ops->delete( tv );
886 if (r == ERROR_SUCCESS)
888 list_add_head( &db->tables, &table->entry );
889 *table_ret = table;
891 else
892 free_table( table );
894 return r;
897 static UINT save_table( MSIDATABASE *db, const MSITABLE *t, UINT bytes_per_strref )
899 BYTE *rawdata = NULL;
900 UINT rawsize, i, j, row_size, row_count;
901 UINT r = ERROR_FUNCTION_FAILED;
903 /* Nothing to do for non-persistent tables */
904 if( t->persistent == MSICONDITION_FALSE )
905 return ERROR_SUCCESS;
907 TRACE("Saving %s\n", debugstr_w( t->name ) );
909 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, bytes_per_strref );
910 row_count = t->row_count;
911 for (i = 0; i < t->row_count; i++)
913 if (!t->data_persistent[i])
915 row_count = 1; /* yes, this is bizarre */
916 break;
919 rawsize = row_count * row_size;
920 rawdata = msi_alloc_zero( rawsize );
921 if( !rawdata )
923 r = ERROR_NOT_ENOUGH_MEMORY;
924 goto err;
927 rawsize = 0;
928 for (i = 0; i < t->row_count; i++)
930 UINT ofs = 0, ofs_mem = 0;
932 if (!t->data_persistent[i]) break;
934 for (j = 0; j < t->col_count; j++)
936 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
937 UINT n = bytes_per_column( db, &t->colinfo[j], bytes_per_strref );
938 UINT k;
940 if (n != 2 && n != 3 && n != 4)
942 ERR("oops - unknown column width %d\n", n);
943 goto err;
945 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
947 UINT id = read_table_int( t->data, i, ofs_mem, LONG_STR_BYTES );
948 if (id > 1 << bytes_per_strref * 8)
950 ERR("string id %u out of range\n", id);
951 goto err;
954 for (k = 0; k < n; k++)
956 rawdata[ofs * row_count + i * n + k] = t->data[i][ofs_mem + k];
958 ofs_mem += m;
959 ofs += n;
961 rawsize += row_size;
964 TRACE("writing %d bytes\n", rawsize);
965 r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
967 err:
968 msi_free( rawdata );
969 return r;
972 static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
974 MSITABLE *table;
975 LPWSTR tablename;
976 UINT size, offset, old_count;
977 UINT n;
979 /* We may free name in msi_free_colinfo. */
980 tablename = strdupW( name );
982 table = find_cached_table( db, tablename );
983 old_count = table->col_count;
984 msi_free_colinfo( table->colinfo, table->col_count );
985 msi_free( table->colinfo );
986 table->colinfo = NULL;
988 table_get_column_info( db, tablename, &table->colinfo, &table->col_count );
989 if (!table->col_count)
990 goto done;
992 size = msi_table_get_row_size( db, table->colinfo, table->col_count, LONG_STR_BYTES );
993 offset = table->colinfo[table->col_count - 1].offset;
995 for ( n = 0; n < table->row_count; n++ )
997 table->data[n] = msi_realloc( table->data[n], size );
998 if (old_count < table->col_count)
999 memset( &table->data[n][offset], 0, size - offset );
1002 done:
1003 msi_free(tablename);
1006 /* try to find the table name in the _Tables table */
1007 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
1009 UINT r, table_id, i;
1010 MSITABLE *table;
1012 if( !strcmpW( name, szTables ) || !strcmpW( name, szColumns ) ||
1013 !strcmpW( name, szStreams ) || !strcmpW( name, szStorages ) )
1014 return TRUE;
1016 r = msi_string2idW( db->strings, name, &table_id );
1017 if( r != ERROR_SUCCESS )
1019 TRACE("Couldn't find id for %s\n", debugstr_w(name));
1020 return FALSE;
1023 r = get_table( db, szTables, &table );
1024 if( r != ERROR_SUCCESS )
1026 ERR("table %s not available\n", debugstr_w(szTables));
1027 return FALSE;
1030 for( i = 0; i < table->row_count; i++ )
1032 if( read_table_int( table->data, i, 0, LONG_STR_BYTES ) == table_id )
1033 return TRUE;
1036 return FALSE;
1039 /* below is the query interface to a table */
1041 typedef struct tagMSITABLEVIEW
1043 MSIVIEW view;
1044 MSIDATABASE *db;
1045 MSITABLE *table;
1046 MSICOLUMNINFO *columns;
1047 MSIORDERINFO *order;
1048 UINT num_cols;
1049 UINT row_size;
1050 WCHAR name[1];
1051 } MSITABLEVIEW;
1053 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1055 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1056 UINT offset, n;
1058 if( !tv->table )
1059 return ERROR_INVALID_PARAMETER;
1061 if( (col==0) || (col>tv->num_cols) )
1062 return ERROR_INVALID_PARAMETER;
1064 /* how many rows are there ? */
1065 if( row >= tv->table->row_count )
1066 return ERROR_NO_MORE_ITEMS;
1068 if( tv->columns[col-1].offset >= tv->row_size )
1070 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1071 ERR("%p %p\n", tv, tv->columns );
1072 return ERROR_FUNCTION_FAILED;
1075 if (tv->order)
1076 row = tv->order->reorder[row];
1078 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1079 if (n != 2 && n != 3 && n != 4)
1081 ERR("oops! what is %d bytes per column?\n", n );
1082 return ERROR_FUNCTION_FAILED;
1085 offset = tv->columns[col-1].offset;
1086 *val = read_table_int(tv->table->data, row, offset, n);
1088 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1090 return ERROR_SUCCESS;
1093 static UINT msi_stream_name( const MSITABLEVIEW *tv, UINT row, LPWSTR *pstname )
1095 LPWSTR p, stname = NULL;
1096 UINT i, r, type, ival;
1097 DWORD len;
1098 LPCWSTR sval;
1099 MSIVIEW *view = (MSIVIEW *) tv;
1101 TRACE("%p %d\n", tv, row);
1103 len = lstrlenW( tv->name ) + 1;
1104 stname = msi_alloc( len*sizeof(WCHAR) );
1105 if ( !stname )
1107 r = ERROR_OUTOFMEMORY;
1108 goto err;
1111 lstrcpyW( stname, tv->name );
1113 for ( i = 0; i < tv->num_cols; i++ )
1115 type = tv->columns[i].type;
1116 if ( type & MSITYPE_KEY )
1118 WCHAR number[0x20];
1120 r = TABLE_fetch_int( view, row, i+1, &ival );
1121 if ( r != ERROR_SUCCESS )
1122 goto err;
1124 if ( tv->columns[i].type & MSITYPE_STRING )
1126 sval = msi_string_lookup_id( tv->db->strings, ival );
1127 if ( !sval )
1129 r = ERROR_INVALID_PARAMETER;
1130 goto err;
1133 else
1135 static const WCHAR fmt[] = { '%','d',0 };
1136 UINT n = bytes_per_column( tv->db, &tv->columns[i], LONG_STR_BYTES );
1138 switch( n )
1140 case 2:
1141 sprintfW( number, fmt, ival-0x8000 );
1142 break;
1143 case 4:
1144 sprintfW( number, fmt, ival^0x80000000 );
1145 break;
1146 default:
1147 ERR( "oops - unknown column width %d\n", n );
1148 r = ERROR_FUNCTION_FAILED;
1149 goto err;
1151 sval = number;
1154 len += lstrlenW( szDot ) + lstrlenW( sval );
1155 p = msi_realloc ( stname, len*sizeof(WCHAR) );
1156 if ( !p )
1158 r = ERROR_OUTOFMEMORY;
1159 goto err;
1161 stname = p;
1163 lstrcatW( stname, szDot );
1164 lstrcatW( stname, sval );
1166 else
1167 continue;
1170 *pstname = stname;
1171 return ERROR_SUCCESS;
1173 err:
1174 msi_free( stname );
1175 *pstname = NULL;
1176 return r;
1180 * We need a special case for streams, as we need to reference column with
1181 * the name of the stream in the same table, and the table name
1182 * which may not be available at higher levels of the query
1184 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1186 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1187 UINT r;
1188 LPWSTR encname, full_name = NULL;
1190 if( !view->ops->fetch_int )
1191 return ERROR_INVALID_PARAMETER;
1193 r = msi_stream_name( tv, row, &full_name );
1194 if ( r != ERROR_SUCCESS )
1196 ERR("fetching stream, error = %d\n", r);
1197 return r;
1200 encname = encode_streamname( FALSE, full_name );
1201 r = msi_get_raw_stream( tv->db, encname, stm );
1202 if( r )
1203 ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1205 msi_free( full_name );
1206 msi_free( encname );
1207 return r;
1210 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1212 UINT offset, n, i;
1214 if( !tv->table )
1215 return ERROR_INVALID_PARAMETER;
1217 if( (col==0) || (col>tv->num_cols) )
1218 return ERROR_INVALID_PARAMETER;
1220 if( row >= tv->table->row_count )
1221 return ERROR_INVALID_PARAMETER;
1223 if( tv->columns[col-1].offset >= tv->row_size )
1225 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1226 ERR("%p %p\n", tv, tv->columns );
1227 return ERROR_FUNCTION_FAILED;
1230 msi_free( tv->columns[col-1].hash_table );
1231 tv->columns[col-1].hash_table = NULL;
1233 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1234 if ( n != 2 && n != 3 && n != 4 )
1236 ERR("oops! what is %d bytes per column?\n", n );
1237 return ERROR_FUNCTION_FAILED;
1240 offset = tv->columns[col-1].offset;
1241 for ( i = 0; i < n; i++ )
1242 tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1244 return ERROR_SUCCESS;
1247 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1249 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1251 if (!tv->table)
1252 return ERROR_INVALID_PARAMETER;
1254 if (tv->order)
1255 row = tv->order->reorder[row];
1257 return msi_view_get_row(tv->db, view, row, rec);
1260 static UINT msi_addstreamW( MSIDATABASE *db, LPCWSTR name, IStream *data )
1262 UINT r;
1263 MSIQUERY *query = NULL;
1264 MSIRECORD *rec = NULL;
1266 static const WCHAR insert[] = {
1267 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1268 '`','_','S','t','r','e','a','m','s','`',' ',
1269 '(','`','N','a','m','e','`',',',
1270 '`','D','a','t','a','`',')',' ',
1271 'V','A','L','U','E','S',' ','(','?',',','?',')',0};
1273 TRACE("%p %s %p\n", db, debugstr_w(name), data);
1275 rec = MSI_CreateRecord( 2 );
1276 if ( !rec )
1277 return ERROR_OUTOFMEMORY;
1279 r = MSI_RecordSetStringW( rec, 1, name );
1280 if ( r != ERROR_SUCCESS )
1281 goto err;
1283 r = MSI_RecordSetIStream( rec, 2, data );
1284 if ( r != ERROR_SUCCESS )
1285 goto err;
1287 r = MSI_DatabaseOpenViewW( db, insert, &query );
1288 if ( r != ERROR_SUCCESS )
1289 goto err;
1291 r = MSI_ViewExecute( query, rec );
1293 err:
1294 msiobj_release( &query->hdr );
1295 msiobj_release( &rec->hdr );
1297 return r;
1300 static UINT get_table_value_from_record( MSITABLEVIEW *tv, MSIRECORD *rec, UINT iField, UINT *pvalue )
1302 MSICOLUMNINFO columninfo;
1303 UINT r;
1305 if ( (iField <= 0) ||
1306 (iField > tv->num_cols) ||
1307 MSI_RecordIsNull( rec, iField ) )
1308 return ERROR_FUNCTION_FAILED;
1310 columninfo = tv->columns[ iField - 1 ];
1312 if ( MSITYPE_IS_BINARY(columninfo.type) )
1314 *pvalue = 1; /* refers to the first key column */
1316 else if ( columninfo.type & MSITYPE_STRING )
1318 LPCWSTR sval = MSI_RecordGetString( rec, iField );
1319 if (sval)
1321 r = msi_string2idW(tv->db->strings, sval, pvalue);
1322 if (r != ERROR_SUCCESS)
1323 return ERROR_NOT_FOUND;
1325 else *pvalue = 0;
1327 else if ( bytes_per_column( tv->db, &columninfo, LONG_STR_BYTES ) == 2 )
1329 *pvalue = 0x8000 + MSI_RecordGetInteger( rec, iField );
1330 if ( *pvalue & 0xffff0000 )
1332 ERR("field %u value %d out of range\n", iField, *pvalue - 0x8000);
1333 return ERROR_FUNCTION_FAILED;
1336 else
1338 INT ival = MSI_RecordGetInteger( rec, iField );
1339 *pvalue = ival ^ 0x80000000;
1342 return ERROR_SUCCESS;
1345 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1347 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1348 UINT i, val, r = ERROR_SUCCESS;
1350 if ( !tv->table )
1351 return ERROR_INVALID_PARAMETER;
1353 /* test if any of the mask bits are invalid */
1354 if ( mask >= (1<<tv->num_cols) )
1355 return ERROR_INVALID_PARAMETER;
1357 for ( i = 0; i < tv->num_cols; i++ )
1359 BOOL persistent;
1361 /* only update the fields specified in the mask */
1362 if ( !(mask&(1<<i)) )
1363 continue;
1365 persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1366 (tv->table->data_persistent[row]);
1367 /* FIXME: should we allow updating keys? */
1369 val = 0;
1370 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1372 r = get_table_value_from_record (tv, rec, i + 1, &val);
1373 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1375 IStream *stm;
1376 LPWSTR stname;
1378 if ( r != ERROR_SUCCESS )
1379 return ERROR_FUNCTION_FAILED;
1381 r = MSI_RecordGetIStream( rec, i + 1, &stm );
1382 if ( r != ERROR_SUCCESS )
1383 return r;
1385 r = msi_stream_name( tv, row, &stname );
1386 if ( r != ERROR_SUCCESS )
1388 IStream_Release( stm );
1389 return r;
1392 r = msi_addstreamW( tv->db, stname, stm );
1393 IStream_Release( stm );
1394 msi_free ( stname );
1396 if ( r != ERROR_SUCCESS )
1397 return r;
1399 else if ( tv->columns[i].type & MSITYPE_STRING )
1401 UINT x;
1403 if ( r != ERROR_SUCCESS )
1405 LPCWSTR sval = MSI_RecordGetString( rec, i + 1 );
1406 val = msi_addstringW( tv->db->strings, sval, -1, 1,
1407 persistent ? StringPersistent : StringNonPersistent );
1409 else
1411 TABLE_fetch_int(&tv->view, row, i + 1, &x);
1412 if (val == x)
1413 continue;
1416 else
1418 if ( r != ERROR_SUCCESS )
1419 return ERROR_FUNCTION_FAILED;
1423 r = TABLE_set_int( tv, row, i+1, val );
1424 if ( r != ERROR_SUCCESS )
1425 break;
1427 return r;
1430 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1432 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1433 BYTE **p, *row;
1434 BOOL *b;
1435 UINT sz;
1436 BYTE ***data_ptr;
1437 BOOL **data_persist_ptr;
1438 UINT *row_count;
1440 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1442 if( !tv->table )
1443 return ERROR_INVALID_PARAMETER;
1445 row = msi_alloc_zero( tv->row_size );
1446 if( !row )
1447 return ERROR_NOT_ENOUGH_MEMORY;
1449 row_count = &tv->table->row_count;
1450 data_ptr = &tv->table->data;
1451 data_persist_ptr = &tv->table->data_persistent;
1452 if (*num == -1)
1453 *num = tv->table->row_count;
1455 sz = (*row_count + 1) * sizeof (BYTE*);
1456 if( *data_ptr )
1457 p = msi_realloc( *data_ptr, sz );
1458 else
1459 p = msi_alloc( sz );
1460 if( !p )
1462 msi_free( row );
1463 return ERROR_NOT_ENOUGH_MEMORY;
1466 sz = (*row_count + 1) * sizeof (BOOL);
1467 if( *data_persist_ptr )
1468 b = msi_realloc( *data_persist_ptr, sz );
1469 else
1470 b = msi_alloc( sz );
1471 if( !b )
1473 msi_free( row );
1474 msi_free( p );
1475 return ERROR_NOT_ENOUGH_MEMORY;
1478 *data_ptr = p;
1479 (*data_ptr)[*row_count] = row;
1481 *data_persist_ptr = b;
1482 (*data_persist_ptr)[*row_count] = !temporary;
1484 (*row_count)++;
1486 return ERROR_SUCCESS;
1489 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1491 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1493 TRACE("%p %p\n", tv, record);
1495 TRACE("There are %d columns\n", tv->num_cols );
1497 return ERROR_SUCCESS;
1500 static UINT TABLE_close( struct tagMSIVIEW *view )
1502 TRACE("%p\n", view );
1504 return ERROR_SUCCESS;
1507 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1509 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1511 TRACE("%p %p %p\n", view, rows, cols );
1513 if( cols )
1514 *cols = tv->num_cols;
1515 if( rows )
1517 if( !tv->table )
1518 return ERROR_INVALID_PARAMETER;
1519 *rows = tv->table->row_count;
1522 return ERROR_SUCCESS;
1525 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1526 UINT n, LPWSTR *name, UINT *type, BOOL *temporary,
1527 LPWSTR *table_name )
1529 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1531 TRACE("%p %d %p %p\n", tv, n, name, type );
1533 if( ( n == 0 ) || ( n > tv->num_cols ) )
1534 return ERROR_INVALID_PARAMETER;
1536 if( name )
1538 *name = strdupW( tv->columns[n-1].colname );
1539 if( !*name )
1540 return ERROR_FUNCTION_FAILED;
1543 if( table_name )
1545 *table_name = strdupW( tv->columns[n-1].tablename );
1546 if( !*table_name )
1547 return ERROR_FUNCTION_FAILED;
1550 if( type )
1551 *type = tv->columns[n-1].type;
1553 if( temporary )
1554 *temporary = tv->columns[n-1].temporary;
1556 return ERROR_SUCCESS;
1559 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column );
1561 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *column )
1563 UINT r, row, i;
1565 /* check there's no null values where they're not allowed */
1566 for( i = 0; i < tv->num_cols; i++ )
1568 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1569 continue;
1571 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1572 TRACE("skipping binary column\n");
1573 else if ( tv->columns[i].type & MSITYPE_STRING )
1575 LPCWSTR str;
1577 str = MSI_RecordGetString( rec, i+1 );
1578 if (str == NULL || str[0] == 0)
1580 if (column) *column = i;
1581 return ERROR_INVALID_DATA;
1584 else
1586 UINT n;
1588 n = MSI_RecordGetInteger( rec, i+1 );
1589 if (n == MSI_NULL_INTEGER)
1591 if (column) *column = i;
1592 return ERROR_INVALID_DATA;
1597 /* check there's no duplicate keys */
1598 r = msi_table_find_row( tv, rec, &row, column );
1599 if (r == ERROR_SUCCESS)
1600 return ERROR_FUNCTION_FAILED;
1602 return ERROR_SUCCESS;
1605 static int compare_record( MSITABLEVIEW *tv, UINT row, MSIRECORD *rec )
1607 UINT r, i, ivalue, x;
1609 for (i = 0; i < tv->num_cols; i++ )
1611 if (!(tv->columns[i].type & MSITYPE_KEY)) continue;
1613 r = get_table_value_from_record( tv, rec, i + 1, &ivalue );
1614 if (r != ERROR_SUCCESS)
1615 return 1;
1617 r = TABLE_fetch_int( &tv->view, row, i + 1, &x );
1618 if (r != ERROR_SUCCESS)
1620 WARN("TABLE_fetch_int should not fail here %u\n", r);
1621 return -1;
1623 if (ivalue > x)
1625 return 1;
1627 else if (ivalue == x)
1629 if (i < tv->num_cols - 1) continue;
1630 return 0;
1632 else
1633 return -1;
1635 return 1;
1638 static int find_insert_index( MSITABLEVIEW *tv, MSIRECORD *rec )
1640 int idx, c, low = 0, high = tv->table->row_count - 1;
1642 TRACE("%p %p\n", tv, rec);
1644 while (low <= high)
1646 idx = (low + high) / 2;
1647 c = compare_record( tv, idx, rec );
1649 if (c < 0)
1650 high = idx - 1;
1651 else if (c > 0)
1652 low = idx + 1;
1653 else
1655 TRACE("found %u\n", idx);
1656 return idx;
1659 TRACE("found %u\n", high + 1);
1660 return high + 1;
1663 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1665 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1666 UINT i, r;
1668 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1670 /* check that the key is unique - can we find a matching row? */
1671 r = table_validate_new( tv, rec, NULL );
1672 if( r != ERROR_SUCCESS )
1673 return ERROR_FUNCTION_FAILED;
1675 if (row == -1)
1676 row = find_insert_index( tv, rec );
1678 r = table_create_new_row( view, &row, temporary );
1679 TRACE("insert_row returned %08x\n", r);
1680 if( r != ERROR_SUCCESS )
1681 return r;
1683 /* shift the rows to make room for the new row */
1684 for (i = tv->table->row_count - 1; i > row; i--)
1686 memmove(&(tv->table->data[i][0]),
1687 &(tv->table->data[i - 1][0]), tv->row_size);
1688 tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1691 /* Re-set the persistence flag */
1692 tv->table->data_persistent[row] = !temporary;
1693 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1696 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1698 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1699 UINT r, num_rows, num_cols, i;
1701 TRACE("%p %d\n", tv, row);
1703 if ( !tv->table )
1704 return ERROR_INVALID_PARAMETER;
1706 r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1707 if ( r != ERROR_SUCCESS )
1708 return r;
1710 if ( row >= num_rows )
1711 return ERROR_FUNCTION_FAILED;
1713 num_rows = tv->table->row_count;
1714 tv->table->row_count--;
1716 /* reset the hash tables */
1717 for (i = 0; i < tv->num_cols; i++)
1719 msi_free( tv->columns[i].hash_table );
1720 tv->columns[i].hash_table = NULL;
1723 for (i = row + 1; i < num_rows; i++)
1725 memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
1726 tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
1729 msi_free(tv->table->data[num_rows - 1]);
1731 return ERROR_SUCCESS;
1734 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1736 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1737 UINT r, new_row;
1739 /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1740 * sets the fetched record apart from other records
1743 if (!tv->table)
1744 return ERROR_INVALID_PARAMETER;
1746 r = msi_table_find_row(tv, rec, &new_row, NULL);
1747 if (r != ERROR_SUCCESS)
1749 ERR("can't find row to modify\n");
1750 return ERROR_FUNCTION_FAILED;
1753 /* the row cannot be changed */
1754 if (row != new_row + 1)
1755 return ERROR_FUNCTION_FAILED;
1757 if(tv->order)
1758 new_row = tv->order->reorder[new_row];
1760 return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1763 static UINT msi_table_assign(struct tagMSIVIEW *view, MSIRECORD *rec)
1765 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1766 UINT r, row;
1768 if (!tv->table)
1769 return ERROR_INVALID_PARAMETER;
1771 r = msi_table_find_row(tv, rec, &row, NULL);
1772 if (r == ERROR_SUCCESS)
1773 return TABLE_set_row(view, row, rec, (1 << tv->num_cols) - 1);
1774 else
1775 return TABLE_insert_row( view, rec, -1, FALSE );
1778 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1780 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1781 UINT row, r;
1783 r = msi_table_find_row(tv, rec, &row, NULL);
1784 if (r != ERROR_SUCCESS)
1785 return r;
1787 return TABLE_delete_row(view, row);
1790 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1792 MSIRECORD *curr;
1793 UINT r, i, count;
1795 r = TABLE_get_row(view, row - 1, &curr);
1796 if (r != ERROR_SUCCESS)
1797 return r;
1799 /* Close the original record */
1800 MSI_CloseRecord(&rec->hdr);
1802 count = MSI_RecordGetFieldCount(rec);
1803 for (i = 0; i < count; i++)
1804 MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1806 msiobj_release(&curr->hdr);
1807 return ERROR_SUCCESS;
1810 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1811 MSIRECORD *rec, UINT row)
1813 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1814 UINT r, column;
1816 TRACE("%p %d %p\n", view, eModifyMode, rec );
1818 switch (eModifyMode)
1820 case MSIMODIFY_DELETE:
1821 r = modify_delete_row( view, rec );
1822 break;
1823 case MSIMODIFY_VALIDATE_NEW:
1824 r = table_validate_new( tv, rec, &column );
1825 if (r != ERROR_SUCCESS)
1827 tv->view.error = MSIDBERROR_DUPLICATEKEY;
1828 tv->view.error_column = tv->columns[column].colname;
1829 r = ERROR_INVALID_DATA;
1831 break;
1833 case MSIMODIFY_INSERT:
1834 r = table_validate_new( tv, rec, NULL );
1835 if (r != ERROR_SUCCESS)
1836 break;
1837 r = TABLE_insert_row( view, rec, -1, FALSE );
1838 break;
1840 case MSIMODIFY_INSERT_TEMPORARY:
1841 r = table_validate_new( tv, rec, NULL );
1842 if (r != ERROR_SUCCESS)
1843 break;
1844 r = TABLE_insert_row( view, rec, -1, TRUE );
1845 break;
1847 case MSIMODIFY_REFRESH:
1848 r = msi_refresh_record( view, rec, row );
1849 break;
1851 case MSIMODIFY_UPDATE:
1852 r = msi_table_update( view, rec, row );
1853 break;
1855 case MSIMODIFY_ASSIGN:
1856 r = msi_table_assign( view, rec );
1857 break;
1859 case MSIMODIFY_REPLACE:
1860 case MSIMODIFY_MERGE:
1861 case MSIMODIFY_VALIDATE:
1862 case MSIMODIFY_VALIDATE_FIELD:
1863 case MSIMODIFY_VALIDATE_DELETE:
1864 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1865 r = ERROR_CALL_NOT_IMPLEMENTED;
1866 break;
1868 default:
1869 r = ERROR_INVALID_DATA;
1872 return r;
1875 static UINT TABLE_delete( struct tagMSIVIEW *view )
1877 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1879 TRACE("%p\n", view );
1881 tv->table = NULL;
1882 tv->columns = NULL;
1884 if (tv->order)
1886 msi_free( tv->order->reorder );
1887 msi_free( tv->order );
1888 tv->order = NULL;
1891 msi_free( tv );
1893 return ERROR_SUCCESS;
1896 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1897 UINT val, UINT *row, MSIITERHANDLE *handle )
1899 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1900 const MSICOLUMNHASHENTRY *entry;
1902 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1904 if( !tv->table )
1905 return ERROR_INVALID_PARAMETER;
1907 if( (col==0) || (col > tv->num_cols) )
1908 return ERROR_INVALID_PARAMETER;
1910 if( !tv->columns[col-1].hash_table )
1912 UINT i;
1913 UINT num_rows = tv->table->row_count;
1914 MSICOLUMNHASHENTRY **hash_table;
1915 MSICOLUMNHASHENTRY *new_entry;
1917 if( tv->columns[col-1].offset >= tv->row_size )
1919 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1920 ERR("%p %p\n", tv, tv->columns );
1921 return ERROR_FUNCTION_FAILED;
1924 /* allocate contiguous memory for the table and its entries so we
1925 * don't have to do an expensive cleanup */
1926 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1927 num_rows * sizeof(MSICOLUMNHASHENTRY));
1928 if (!hash_table)
1929 return ERROR_OUTOFMEMORY;
1931 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1932 tv->columns[col-1].hash_table = hash_table;
1934 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1936 for (i = 0; i < num_rows; i++, new_entry++)
1938 UINT row_value;
1940 if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1941 continue;
1943 new_entry->next = NULL;
1944 new_entry->value = row_value;
1945 new_entry->row = i;
1946 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1948 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1949 while (prev_entry->next)
1950 prev_entry = prev_entry->next;
1951 prev_entry->next = new_entry;
1953 else
1954 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1958 if( !*handle )
1959 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1960 else
1961 entry = (*handle)->next;
1963 while (entry && entry->value != val)
1964 entry = entry->next;
1966 *handle = entry;
1967 if (!entry)
1968 return ERROR_NO_MORE_ITEMS;
1970 *row = entry->row;
1972 return ERROR_SUCCESS;
1975 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1977 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1978 UINT i;
1980 TRACE("%p %d\n", view, tv->table->ref_count);
1982 for (i = 0; i < tv->table->col_count; i++)
1984 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1985 InterlockedIncrement(&tv->table->colinfo[i].ref_count);
1988 return InterlockedIncrement(&tv->table->ref_count);
1991 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
1993 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1994 MSIRECORD *rec = NULL;
1995 MSIVIEW *columns = NULL;
1996 UINT row, r;
1998 rec = MSI_CreateRecord(2);
1999 if (!rec)
2000 return ERROR_OUTOFMEMORY;
2002 MSI_RecordSetStringW(rec, 1, table);
2003 MSI_RecordSetInteger(rec, 2, number);
2005 r = TABLE_CreateView(tv->db, szColumns, &columns);
2006 if (r != ERROR_SUCCESS)
2007 return r;
2009 r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row, NULL);
2010 if (r != ERROR_SUCCESS)
2011 goto done;
2013 r = TABLE_delete_row(columns, row);
2014 if (r != ERROR_SUCCESS)
2015 goto done;
2017 msi_update_table_columns(tv->db, table);
2019 done:
2020 msiobj_release(&rec->hdr);
2021 columns->ops->delete(columns);
2022 return r;
2025 static UINT TABLE_release(struct tagMSIVIEW *view)
2027 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2028 INT ref = tv->table->ref_count;
2029 UINT i, r;
2031 TRACE("%p %d\n", view, ref);
2033 for (i = 0; i < tv->table->col_count; i++)
2035 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
2037 ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
2038 if (ref == 0)
2040 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2041 tv->table->colinfo[i].number);
2042 if (r != ERROR_SUCCESS)
2043 break;
2048 ref = InterlockedDecrement(&tv->table->ref_count);
2049 if (ref == 0)
2051 if (!tv->table->row_count)
2053 list_remove(&tv->table->entry);
2054 free_table(tv->table);
2055 TABLE_delete(view);
2059 return ref;
2062 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
2063 LPCWSTR column, UINT type, BOOL hold)
2065 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2066 MSITABLE *msitable;
2067 MSIRECORD *rec;
2068 UINT r, i;
2070 rec = MSI_CreateRecord(4);
2071 if (!rec)
2072 return ERROR_OUTOFMEMORY;
2074 MSI_RecordSetStringW(rec, 1, table);
2075 MSI_RecordSetInteger(rec, 2, number);
2076 MSI_RecordSetStringW(rec, 3, column);
2077 MSI_RecordSetInteger(rec, 4, type);
2079 r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
2080 if (r != ERROR_SUCCESS)
2081 goto done;
2083 msi_update_table_columns(tv->db, table);
2085 if (!hold)
2086 goto done;
2088 msitable = find_cached_table(tv->db, table);
2089 for (i = 0; i < msitable->col_count; i++)
2091 if (!strcmpW( msitable->colinfo[i].colname, column ))
2093 InterlockedIncrement(&msitable->colinfo[i].ref_count);
2094 break;
2098 done:
2099 msiobj_release(&rec->hdr);
2100 return r;
2103 static UINT order_add_column(struct tagMSIVIEW *view, MSIORDERINFO *order, LPCWSTR name)
2105 UINT n, r, count;
2106 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2108 r = TABLE_get_dimensions(view, NULL, &count);
2109 if (r != ERROR_SUCCESS)
2110 return r;
2112 if (order->num_cols >= count)
2113 return ERROR_FUNCTION_FAILED;
2115 r = VIEW_find_column(view, name, tv->name, &n);
2116 if (r != ERROR_SUCCESS)
2117 return r;
2119 order->cols[order->num_cols] = n;
2120 TRACE("Ordering by column %s (%d)\n", debugstr_w(name), n);
2122 order->num_cols++;
2124 return ERROR_SUCCESS;
2127 static UINT order_compare(struct tagMSIVIEW *view, MSIORDERINFO *order,
2128 UINT a, UINT b, UINT *swap)
2130 UINT r, i, a_val = 0, b_val = 0;
2132 *swap = 0;
2133 for (i = 0; i < order->num_cols; i++)
2135 r = TABLE_fetch_int(view, a, order->cols[i], &a_val);
2136 if (r != ERROR_SUCCESS)
2137 return r;
2139 r = TABLE_fetch_int(view, b, order->cols[i], &b_val);
2140 if (r != ERROR_SUCCESS)
2141 return r;
2143 if (a_val != b_val)
2145 if (a_val > b_val)
2146 *swap = 1;
2147 break;
2151 return ERROR_SUCCESS;
2154 static UINT order_mergesort(struct tagMSIVIEW *view, MSIORDERINFO *order,
2155 UINT left, UINT right)
2157 UINT r, i, j, temp;
2158 UINT swap = 0, center = (left + right) / 2;
2159 UINT *array = order->reorder;
2161 if (left == right)
2162 return ERROR_SUCCESS;
2164 /* sort the left half */
2165 r = order_mergesort(view, order, left, center);
2166 if (r != ERROR_SUCCESS)
2167 return r;
2169 /* sort the right half */
2170 r = order_mergesort(view, order, center + 1, right);
2171 if (r != ERROR_SUCCESS)
2172 return r;
2174 for (i = left, j = center + 1; (i <= center) && (j <= right); i++)
2176 r = order_compare(view, order, array[i], array[j], &swap);
2177 if (r != ERROR_SUCCESS)
2178 return r;
2180 if (swap)
2182 temp = array[j];
2183 memmove(&array[i + 1], &array[i], (j - i) * sizeof(UINT));
2184 array[i] = temp;
2185 j++;
2186 center++;
2190 return ERROR_SUCCESS;
2193 static UINT order_verify(struct tagMSIVIEW *view, MSIORDERINFO *order, UINT num_rows)
2195 UINT i, swap, r;
2197 for (i = 1; i < num_rows; i++)
2199 r = order_compare(view, order, order->reorder[i - 1],
2200 order->reorder[i], &swap);
2201 if (r != ERROR_SUCCESS)
2202 return r;
2204 if (!swap)
2205 continue;
2207 ERR("Bad order! %d\n", i);
2208 return ERROR_FUNCTION_FAILED;
2211 return ERROR_SUCCESS;
2214 static UINT TABLE_sort(struct tagMSIVIEW *view, column_info *columns)
2216 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
2217 MSIORDERINFO *order;
2218 column_info *ptr;
2219 UINT r, i;
2220 UINT rows, cols;
2222 TRACE("sorting table %s\n", debugstr_w(tv->name));
2224 r = TABLE_get_dimensions(view, &rows, &cols);
2225 if (r != ERROR_SUCCESS)
2226 return r;
2228 if (rows == 0)
2229 return ERROR_SUCCESS;
2231 order = msi_alloc_zero(sizeof(MSIORDERINFO) + sizeof(UINT) * cols);
2232 if (!order)
2233 return ERROR_OUTOFMEMORY;
2235 for (ptr = columns; ptr; ptr = ptr->next)
2236 order_add_column(view, order, ptr->column);
2238 order->reorder = msi_alloc(rows * sizeof(UINT));
2239 if (!order->reorder)
2240 return ERROR_OUTOFMEMORY;
2242 for (i = 0; i < rows; i++)
2243 order->reorder[i] = i;
2245 r = order_mergesort(view, order, 0, rows - 1);
2246 if (r != ERROR_SUCCESS)
2247 return r;
2249 r = order_verify(view, order, rows);
2250 if (r != ERROR_SUCCESS)
2251 return r;
2253 tv->order = order;
2255 return ERROR_SUCCESS;
2258 static UINT TABLE_drop(struct tagMSIVIEW *view)
2260 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2261 MSIVIEW *tables = NULL;
2262 MSIRECORD *rec = NULL;
2263 UINT r, row;
2264 INT i;
2266 TRACE("dropping table %s\n", debugstr_w(tv->name));
2268 for (i = tv->table->col_count - 1; i >= 0; i--)
2270 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2271 tv->table->colinfo[i].number);
2272 if (r != ERROR_SUCCESS)
2273 return r;
2276 rec = MSI_CreateRecord(1);
2277 if (!rec)
2278 return ERROR_OUTOFMEMORY;
2280 MSI_RecordSetStringW(rec, 1, tv->name);
2282 r = TABLE_CreateView(tv->db, szTables, &tables);
2283 if (r != ERROR_SUCCESS)
2284 return r;
2286 r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row, NULL);
2287 if (r != ERROR_SUCCESS)
2288 goto done;
2290 r = TABLE_delete_row(tables, row);
2291 if (r != ERROR_SUCCESS)
2292 goto done;
2294 list_remove(&tv->table->entry);
2295 free_table(tv->table);
2297 done:
2298 msiobj_release(&rec->hdr);
2299 tables->ops->delete(tables);
2301 return r;
2304 static const MSIVIEWOPS table_ops =
2306 TABLE_fetch_int,
2307 TABLE_fetch_stream,
2308 TABLE_get_row,
2309 TABLE_set_row,
2310 TABLE_insert_row,
2311 TABLE_delete_row,
2312 TABLE_execute,
2313 TABLE_close,
2314 TABLE_get_dimensions,
2315 TABLE_get_column_info,
2316 TABLE_modify,
2317 TABLE_delete,
2318 TABLE_find_matching_rows,
2319 TABLE_add_ref,
2320 TABLE_release,
2321 TABLE_add_column,
2322 TABLE_remove_column,
2323 TABLE_sort,
2324 TABLE_drop,
2327 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2329 MSITABLEVIEW *tv ;
2330 UINT r, sz;
2332 TRACE("%p %s %p\n", db, debugstr_w(name), view );
2334 if ( !strcmpW( name, szStreams ) )
2335 return STREAMS_CreateView( db, view );
2336 else if ( !strcmpW( name, szStorages ) )
2337 return STORAGES_CreateView( db, view );
2339 sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
2340 tv = msi_alloc_zero( sz );
2341 if( !tv )
2342 return ERROR_FUNCTION_FAILED;
2344 r = get_table( db, name, &tv->table );
2345 if( r != ERROR_SUCCESS )
2347 msi_free( tv );
2348 WARN("table not found\n");
2349 return r;
2352 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2354 /* fill the structure */
2355 tv->view.ops = &table_ops;
2356 tv->db = db;
2357 tv->columns = tv->table->colinfo;
2358 tv->num_cols = tv->table->col_count;
2359 tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count, LONG_STR_BYTES );
2361 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2363 *view = (MSIVIEW*) tv;
2364 lstrcpyW( tv->name, name );
2366 return ERROR_SUCCESS;
2369 UINT MSI_CommitTables( MSIDATABASE *db )
2371 UINT r, bytes_per_strref;
2372 HRESULT hr;
2373 MSITABLE *table = NULL;
2375 TRACE("%p\n",db);
2377 r = msi_save_string_table( db->strings, db->storage, &bytes_per_strref );
2378 if( r != ERROR_SUCCESS )
2380 WARN("failed to save string table r=%08x\n",r);
2381 return r;
2384 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2386 r = save_table( db, table, bytes_per_strref );
2387 if( r != ERROR_SUCCESS )
2389 WARN("failed to save table %s (r=%08x)\n",
2390 debugstr_w(table->name), r);
2391 return r;
2395 /* force everything to reload next time */
2396 free_cached_tables( db );
2398 hr = IStorage_Commit( db->storage, 0 );
2399 if (FAILED( hr ))
2401 WARN("failed to commit changes 0x%08x\n", hr);
2402 r = ERROR_FUNCTION_FAILED;
2404 return r;
2407 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2409 MSITABLE *t;
2410 UINT r;
2412 TRACE("%p %s\n", db, debugstr_w(table));
2414 if (!table)
2415 return MSICONDITION_ERROR;
2417 r = get_table( db, table, &t );
2418 if (r != ERROR_SUCCESS)
2419 return MSICONDITION_NONE;
2421 return t->persistent;
2424 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2426 UINT ret = 0, i;
2428 for (i = 0; i < bytes; i++)
2429 ret += (data[col + i] << i * 8);
2431 return ret;
2434 static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
2436 LPWSTR stname = NULL, sval, p;
2437 DWORD len;
2438 UINT i, r;
2440 TRACE("%p %p\n", tv, rec);
2442 len = lstrlenW( tv->name ) + 1;
2443 stname = msi_alloc( len*sizeof(WCHAR) );
2444 if ( !stname )
2446 r = ERROR_OUTOFMEMORY;
2447 goto err;
2450 lstrcpyW( stname, tv->name );
2452 for ( i = 0; i < tv->num_cols; i++ )
2454 if ( tv->columns[i].type & MSITYPE_KEY )
2456 sval = msi_dup_record_field( rec, i + 1 );
2457 if ( !sval )
2459 r = ERROR_OUTOFMEMORY;
2460 goto err;
2463 len += lstrlenW( szDot ) + lstrlenW ( sval );
2464 p = msi_realloc ( stname, len*sizeof(WCHAR) );
2465 if ( !p )
2467 r = ERROR_OUTOFMEMORY;
2468 goto err;
2470 stname = p;
2472 lstrcatW( stname, szDot );
2473 lstrcatW( stname, sval );
2475 msi_free( sval );
2477 else
2478 continue;
2481 *pstname = encode_streamname( FALSE, stname );
2482 msi_free( stname );
2484 return ERROR_SUCCESS;
2486 err:
2487 msi_free ( stname );
2488 *pstname = NULL;
2489 return r;
2492 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2493 IStorage *stg,
2494 const BYTE *rawdata, UINT bytes_per_strref )
2496 UINT i, val, ofs = 0;
2497 USHORT mask;
2498 MSICOLUMNINFO *columns = tv->columns;
2499 MSIRECORD *rec;
2501 mask = rawdata[0] | (rawdata[1] << 8);
2502 rawdata += 2;
2504 rec = MSI_CreateRecord( tv->num_cols );
2505 if( !rec )
2506 return rec;
2508 TRACE("row ->\n");
2509 for( i=0; i<tv->num_cols; i++ )
2511 if ( (mask&1) && (i>=(mask>>8)) )
2512 break;
2513 /* all keys must be present */
2514 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2515 continue;
2517 if( MSITYPE_IS_BINARY(tv->columns[i].type) )
2519 LPWSTR encname;
2520 IStream *stm = NULL;
2521 UINT r;
2523 ofs += bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2525 r = msi_record_encoded_stream_name( tv, rec, &encname );
2526 if ( r != ERROR_SUCCESS )
2527 return NULL;
2529 r = IStorage_OpenStream( stg, encname, NULL,
2530 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
2531 msi_free( encname );
2532 if ( r != ERROR_SUCCESS )
2533 return NULL;
2535 MSI_RecordSetStream( rec, i+1, stm );
2536 TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
2538 else if( columns[i].type & MSITYPE_STRING )
2540 LPCWSTR sval;
2542 val = read_raw_int(rawdata, ofs, bytes_per_strref);
2543 sval = msi_string_lookup_id( st, val );
2544 MSI_RecordSetStringW( rec, i+1, sval );
2545 TRACE(" field %d [%s]\n", i+1, debugstr_w(sval));
2546 ofs += bytes_per_strref;
2548 else
2550 UINT n = bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2551 switch( n )
2553 case 2:
2554 val = read_raw_int(rawdata, ofs, n);
2555 if (val)
2556 MSI_RecordSetInteger( rec, i+1, val-0x8000 );
2557 TRACE(" field %d [0x%04x]\n", i+1, val );
2558 break;
2559 case 4:
2560 val = read_raw_int(rawdata, ofs, n);
2561 if (val)
2562 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2563 TRACE(" field %d [0x%08x]\n", i+1, val );
2564 break;
2565 default:
2566 ERR("oops - unknown column width %d\n", n);
2567 break;
2569 ofs += n;
2572 return rec;
2575 static void dump_record( MSIRECORD *rec )
2577 UINT i, n;
2579 n = MSI_RecordGetFieldCount( rec );
2580 for( i=1; i<=n; i++ )
2582 LPCWSTR sval;
2584 if( MSI_RecordIsNull( rec, i ) )
2585 TRACE("row -> []\n");
2586 else if( (sval = MSI_RecordGetString( rec, i )) )
2587 TRACE("row -> [%s]\n", debugstr_w(sval));
2588 else
2589 TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2593 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2595 LPCWSTR sval;
2596 UINT i;
2598 for( i=0; i<(rawsize/2); i++ )
2600 sval = msi_string_lookup_id( st, rawdata[i] );
2601 MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
2605 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2607 LPCWSTR str;
2608 UINT i, r, *data;
2610 data = msi_alloc( tv->num_cols *sizeof (UINT) );
2611 for( i=0; i<tv->num_cols; i++ )
2613 data[i] = 0;
2615 if ( ~tv->columns[i].type & MSITYPE_KEY )
2616 continue;
2618 /* turn the transform column value into a row value */
2619 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2620 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2622 str = MSI_RecordGetString( rec, i+1 );
2623 if (str)
2625 r = msi_string2idW( tv->db->strings, str, &data[i] );
2627 /* if there's no matching string in the string table,
2628 these keys can't match any record, so fail now. */
2629 if (r != ERROR_SUCCESS)
2631 msi_free( data );
2632 return NULL;
2635 else data[i] = 0;
2637 else
2639 data[i] = MSI_RecordGetInteger( rec, i+1 );
2641 if (data[i] == MSI_NULL_INTEGER)
2642 data[i] = 0;
2643 else if ((tv->columns[i].type&0xff) == 2)
2644 data[i] += 0x8000;
2645 else
2646 data[i] += 0x80000000;
2649 return data;
2652 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data, UINT *column )
2654 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2656 for( i=0; i<tv->num_cols; i++ )
2658 if ( ~tv->columns[i].type & MSITYPE_KEY )
2659 continue;
2661 /* turn the transform column value into a row value */
2662 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2663 if ( r != ERROR_SUCCESS )
2665 ERR("TABLE_fetch_int shouldn't fail here\n");
2666 break;
2669 /* if this key matches, move to the next column */
2670 if ( x != data[i] )
2672 ret = ERROR_FUNCTION_FAILED;
2673 break;
2675 if (column) *column = i;
2676 ret = ERROR_SUCCESS;
2678 return ret;
2681 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column )
2683 UINT i, r = ERROR_FUNCTION_FAILED, *data;
2685 data = msi_record_to_row( tv, rec );
2686 if( !data )
2687 return r;
2688 for( i = 0; i < tv->table->row_count; i++ )
2690 r = msi_row_matches( tv, i, data, column );
2691 if( r == ERROR_SUCCESS )
2693 *row = i;
2694 break;
2697 msi_free( data );
2698 return r;
2701 typedef struct
2703 struct list entry;
2704 LPWSTR name;
2705 } TRANSFORMDATA;
2707 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2708 string_table *st, TRANSFORMDATA *transform,
2709 UINT bytes_per_strref )
2711 UINT rawsize = 0;
2712 BYTE *rawdata = NULL;
2713 MSITABLEVIEW *tv = NULL;
2714 UINT r, n, sz, i, mask;
2715 MSIRECORD *rec = NULL;
2716 UINT colcol = 0;
2717 WCHAR coltable[32];
2718 LPWSTR name;
2720 if (!transform)
2721 return ERROR_SUCCESS;
2723 name = transform->name;
2725 coltable[0] = 0;
2726 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2728 /* read the transform data */
2729 read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2730 if ( !rawdata )
2732 TRACE("table %s empty\n", debugstr_w(name) );
2733 return ERROR_INVALID_TABLE;
2736 /* create a table view */
2737 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2738 if( r != ERROR_SUCCESS )
2739 goto err;
2741 r = tv->view.ops->execute( &tv->view, NULL );
2742 if( r != ERROR_SUCCESS )
2743 goto err;
2745 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2746 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2748 /* interpret the data */
2749 r = ERROR_SUCCESS;
2750 for( n=0; n < rawsize; )
2752 mask = rawdata[n] | (rawdata[n+1] << 8);
2754 if (mask&1)
2757 * if the low bit is set, columns are continuous and
2758 * the number of columns is specified in the high byte
2760 sz = 2;
2761 for( i=0; i<tv->num_cols; i++ )
2763 if( (tv->columns[i].type & MSITYPE_STRING) &&
2764 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2765 sz += bytes_per_strref;
2766 else
2767 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2770 else
2773 * If the low bit is not set, mask is a bitmask.
2774 * Excepting for key fields, which are always present,
2775 * each bit indicates that a field is present in the transform record.
2777 * mask == 0 is a special case ... only the keys will be present
2778 * and it means that this row should be deleted.
2780 sz = 2;
2781 for( i=0; i<tv->num_cols; i++ )
2783 if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
2785 if( (tv->columns[i].type & MSITYPE_STRING) &&
2786 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2787 sz += bytes_per_strref;
2788 else
2789 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2794 /* check we didn't run of the end of the table */
2795 if ( (n+sz) > rawsize )
2797 ERR("borked.\n");
2798 dump_table( st, (USHORT *)rawdata, rawsize );
2799 break;
2802 rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2803 if (rec)
2805 WCHAR table[32];
2806 DWORD sz = 32;
2807 UINT number = MSI_NULL_INTEGER;
2808 UINT row = 0;
2810 if (!strcmpW( name, szColumns ))
2812 MSI_RecordGetStringW( rec, 1, table, &sz );
2813 number = MSI_RecordGetInteger( rec, 2 );
2816 * Native msi seems writes nul into the Number (2nd) column of
2817 * the _Columns table, only when the columns are from a new table
2819 if ( number == MSI_NULL_INTEGER )
2821 /* reset the column number on a new table */
2822 if (strcmpW( coltable, table ))
2824 colcol = 0;
2825 lstrcpyW( coltable, table );
2828 /* fix nul column numbers */
2829 MSI_RecordSetInteger( rec, 2, ++colcol );
2833 if (TRACE_ON(msidb)) dump_record( rec );
2835 r = msi_table_find_row( tv, rec, &row, NULL );
2836 if (r == ERROR_SUCCESS)
2838 if (!mask)
2840 TRACE("deleting row [%d]:\n", row);
2841 r = TABLE_delete_row( &tv->view, row );
2842 if (r != ERROR_SUCCESS)
2843 WARN("failed to delete row %u\n", r);
2845 else if (mask & 1)
2847 TRACE("modifying full row [%d]:\n", row);
2848 r = TABLE_set_row( &tv->view, row, rec, (1 << tv->num_cols) - 1 );
2849 if (r != ERROR_SUCCESS)
2850 WARN("failed to modify row %u\n", r);
2852 else
2854 TRACE("modifying masked row [%d]:\n", row);
2855 r = TABLE_set_row( &tv->view, row, rec, mask );
2856 if (r != ERROR_SUCCESS)
2857 WARN("failed to modify row %u\n", r);
2860 else
2862 TRACE("inserting row\n");
2863 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2864 if (r != ERROR_SUCCESS)
2865 WARN("failed to insert row %u\n", r);
2868 if (number != MSI_NULL_INTEGER && !strcmpW( name, szColumns ))
2869 msi_update_table_columns( db, table );
2871 msiobj_release( &rec->hdr );
2874 n += sz;
2877 err:
2878 /* no need to free the table, it's associated with the database */
2879 msi_free( rawdata );
2880 if( tv )
2881 tv->view.ops->delete( &tv->view );
2883 return ERROR_SUCCESS;
2887 * msi_table_apply_transform
2889 * Enumerate the table transforms in a transform storage and apply each one.
2891 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2893 struct list transforms;
2894 IEnumSTATSTG *stgenum = NULL;
2895 TRANSFORMDATA *transform;
2896 TRANSFORMDATA *tables = NULL, *columns = NULL;
2897 HRESULT r;
2898 STATSTG stat;
2899 string_table *strings;
2900 UINT ret = ERROR_FUNCTION_FAILED;
2901 UINT bytes_per_strref;
2903 TRACE("%p %p\n", db, stg );
2905 strings = msi_load_string_table( stg, &bytes_per_strref );
2906 if( !strings )
2907 goto end;
2909 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2910 if( FAILED( r ) )
2911 goto end;
2913 list_init(&transforms);
2915 while ( TRUE )
2917 MSITABLEVIEW *tv = NULL;
2918 WCHAR name[0x40];
2919 ULONG count = 0;
2921 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2922 if ( FAILED( r ) || !count )
2923 break;
2925 decode_streamname( stat.pwcsName, name );
2926 CoTaskMemFree( stat.pwcsName );
2927 if ( name[0] != 0x4840 )
2928 continue;
2930 if ( !strcmpW( name+1, szStringPool ) ||
2931 !strcmpW( name+1, szStringData ) )
2932 continue;
2934 transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2935 if ( !transform )
2936 break;
2938 list_add_tail( &transforms, &transform->entry );
2940 transform->name = strdupW( name + 1 );
2942 if ( !strcmpW( transform->name, szTables ) )
2943 tables = transform;
2944 else if (!strcmpW( transform->name, szColumns ) )
2945 columns = transform;
2947 TRACE("transform contains stream %s\n", debugstr_w(name));
2949 /* load the table */
2950 r = TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv );
2951 if( r != ERROR_SUCCESS )
2952 continue;
2954 r = tv->view.ops->execute( &tv->view, NULL );
2955 if( r != ERROR_SUCCESS )
2957 tv->view.ops->delete( &tv->view );
2958 continue;
2961 tv->view.ops->delete( &tv->view );
2965 * Apply _Tables and _Columns transforms first so that
2966 * the table metadata is correct, and empty tables exist.
2968 ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2969 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2970 goto end;
2972 ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2973 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2974 goto end;
2976 ret = ERROR_SUCCESS;
2978 while ( !list_empty( &transforms ) )
2980 transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2982 if ( strcmpW( transform->name, szColumns ) &&
2983 strcmpW( transform->name, szTables ) &&
2984 ret == ERROR_SUCCESS )
2986 ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
2989 list_remove( &transform->entry );
2990 msi_free( transform->name );
2991 msi_free( transform );
2994 if ( ret == ERROR_SUCCESS )
2995 append_storage_to_db( db, stg );
2997 end:
2998 if ( stgenum )
2999 IEnumSTATSTG_Release( stgenum );
3000 if ( strings )
3001 msi_destroy_stringtable( strings );
3003 return ret;