msi: Handle embedded nulls in text archives.
[wine/multimedia.git] / dlls / msi / database.c
blobe7164e56011388c9a8a876ab7248e14634d8e830
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
4 * Copyright 2002,2003,2004,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 <stdio.h>
24 #define COBJMACROS
25 #define NONAMELESSUNION
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winreg.h"
30 #include "winnls.h"
31 #include "wine/debug.h"
32 #include "wine/unicode.h"
33 #include "msi.h"
34 #include "msiquery.h"
35 #include "msipriv.h"
36 #include "objidl.h"
37 #include "objbase.h"
38 #include "msiserver.h"
39 #include "query.h"
41 #include "initguid.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(msi);
46 * .MSI file format
48 * An .msi file is a structured storage file.
49 * It contains a number of streams.
50 * A stream for each table in the database.
51 * Two streams for the string table in the database.
52 * Any binary data in a table is a reference to a stream.
55 #define IS_INTMSIDBOPEN(x) (((ULONG_PTR)(x) >> 16) == 0)
57 typedef struct tagMSITRANSFORM {
58 struct list entry;
59 IStorage *stg;
60 } MSITRANSFORM;
62 typedef struct tagMSISTREAM {
63 struct list entry;
64 IStorage *stg;
65 IStream *stm;
66 } MSISTREAM;
68 static UINT find_open_stream( MSIDATABASE *db, IStorage *stg, LPCWSTR name, IStream **stm )
70 MSISTREAM *stream;
72 LIST_FOR_EACH_ENTRY( stream, &db->streams, MSISTREAM, entry )
74 HRESULT r;
75 STATSTG stat;
77 if (stream->stg != stg) continue;
79 r = IStream_Stat( stream->stm, &stat, 0 );
80 if( FAILED( r ) )
82 WARN("failed to stat stream r = %08x!\n", r);
83 continue;
86 if( !strcmpW( name, stat.pwcsName ) )
88 TRACE("found %s\n", debugstr_w(name));
89 *stm = stream->stm;
90 CoTaskMemFree( stat.pwcsName );
91 return ERROR_SUCCESS;
94 CoTaskMemFree( stat.pwcsName );
97 return ERROR_FUNCTION_FAILED;
100 UINT msi_clone_open_stream( MSIDATABASE *db, IStorage *stg, LPCWSTR name, IStream **stm )
102 IStream *stream;
104 if (find_open_stream( db, stg, name, &stream ) == ERROR_SUCCESS)
106 HRESULT r;
107 LARGE_INTEGER pos;
109 r = IStream_Clone( stream, stm );
110 if( FAILED( r ) )
112 WARN("failed to clone stream r = %08x!\n", r);
113 return ERROR_FUNCTION_FAILED;
116 pos.QuadPart = 0;
117 r = IStream_Seek( *stm, pos, STREAM_SEEK_SET, NULL );
118 if( FAILED( r ) )
120 IStream_Release( *stm );
121 return ERROR_FUNCTION_FAILED;
124 return ERROR_SUCCESS;
127 return ERROR_FUNCTION_FAILED;
130 UINT msi_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
132 HRESULT r;
133 IStorage *stg;
134 WCHAR decoded[MAX_STREAM_NAME_LEN];
136 decode_streamname( stname, decoded );
137 TRACE("%s -> %s\n", debugstr_w(stname), debugstr_w(decoded));
139 if (msi_clone_open_stream( db, db->storage, stname, stm ) == ERROR_SUCCESS)
140 return ERROR_SUCCESS;
142 r = IStorage_OpenStream( db->storage, stname, NULL,
143 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
144 if( FAILED( r ) )
146 MSITRANSFORM *transform;
148 LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
150 r = IStorage_OpenStream( transform->stg, stname, NULL,
151 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
152 if (SUCCEEDED(r))
154 stg = transform->stg;
155 break;
159 else stg = db->storage;
161 if( SUCCEEDED(r) )
163 MSISTREAM *stream;
165 if (!(stream = msi_alloc( sizeof(MSISTREAM) ))) return ERROR_NOT_ENOUGH_MEMORY;
166 stream->stg = stg;
167 IStream_AddRef( stg );
168 stream->stm = *stm;
169 IStream_AddRef( *stm );
170 list_add_tail( &db->streams, &stream->entry );
173 return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
176 static void free_transforms( MSIDATABASE *db )
178 while( !list_empty( &db->transforms ) )
180 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
181 MSITRANSFORM, entry );
182 list_remove( &t->entry );
183 IStorage_Release( t->stg );
184 msi_free( t );
188 void msi_destroy_stream( MSIDATABASE *db, const WCHAR *stname )
190 MSISTREAM *stream, *stream2;
192 LIST_FOR_EACH_ENTRY_SAFE( stream, stream2, &db->streams, MSISTREAM, entry )
194 HRESULT r;
195 STATSTG stat;
197 r = IStream_Stat( stream->stm, &stat, 0 );
198 if (FAILED(r))
200 WARN("failed to stat stream r = %08x\n", r);
201 continue;
204 if (!strcmpW( stname, stat.pwcsName ))
206 TRACE("destroying %s\n", debugstr_w(stname));
208 list_remove( &stream->entry );
209 IStream_Release( stream->stm );
210 IStream_Release( stream->stg );
211 IStorage_DestroyElement( stream->stg, stname );
212 msi_free( stream );
213 CoTaskMemFree( stat.pwcsName );
214 break;
216 CoTaskMemFree( stat.pwcsName );
220 static void free_streams( MSIDATABASE *db )
222 while( !list_empty( &db->streams ) )
224 MSISTREAM *s = LIST_ENTRY(list_head( &db->streams ), MSISTREAM, entry);
225 list_remove( &s->entry );
226 IStream_Release( s->stm );
227 IStream_Release( s->stg );
228 msi_free( s );
232 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
234 MSITRANSFORM *t;
236 t = msi_alloc( sizeof *t );
237 t->stg = stg;
238 IStorage_AddRef( stg );
239 list_add_head( &db->transforms, &t->entry );
241 /* the transform may add or replace streams */
242 free_streams( db );
245 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
247 MSIDATABASE *db = (MSIDATABASE *) arg;
249 msi_free(db->path);
250 free_cached_tables( db );
251 free_streams( db );
252 free_transforms( db );
253 if (db->strings) msi_destroy_stringtable( db->strings );
254 IStorage_Release( db->storage );
255 if (db->deletefile)
257 DeleteFileW( db->deletefile );
258 msi_free( db->deletefile );
260 if (db->localfile)
262 DeleteFileW( db->localfile );
263 msi_free( db->localfile );
267 static HRESULT db_initialize( IStorage *stg, const GUID *clsid )
269 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
270 HRESULT hr;
272 hr = IStorage_SetClass( stg, clsid );
273 if (FAILED( hr ))
275 WARN("failed to set class id 0x%08x\n", hr);
276 return hr;
279 /* create the _Tables stream */
280 hr = write_stream_data( stg, szTables, NULL, 0, TRUE );
281 if (FAILED( hr ))
283 WARN("failed to create _Tables stream 0x%08x\n", hr);
284 return hr;
287 hr = msi_init_string_table( stg );
288 if (FAILED( hr ))
290 WARN("failed to initialize string table 0x%08x\n", hr);
291 return hr;
294 hr = IStorage_Commit( stg, 0 );
295 if (FAILED( hr ))
297 WARN("failed to commit changes 0x%08x\n", hr);
298 return hr;
301 return S_OK;
304 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
306 IStorage *stg = NULL;
307 HRESULT r;
308 MSIDATABASE *db = NULL;
309 UINT ret = ERROR_FUNCTION_FAILED;
310 LPCWSTR szMode, save_path;
311 STATSTG stat;
312 BOOL created = FALSE, patch = FALSE;
313 WCHAR path[MAX_PATH];
315 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
317 if( !pdb )
318 return ERROR_INVALID_PARAMETER;
320 if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
321 szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
323 TRACE("Database is a patch\n");
324 szPersist -= MSIDBOPEN_PATCHFILE;
325 patch = TRUE;
328 save_path = szDBPath;
329 szMode = szPersist;
330 if( !IS_INTMSIDBOPEN(szPersist) )
332 if (!CopyFileW( szDBPath, szPersist, FALSE ))
333 return ERROR_OPEN_FAILED;
335 szDBPath = szPersist;
336 szPersist = MSIDBOPEN_TRANSACT;
337 created = TRUE;
340 if( szPersist == MSIDBOPEN_READONLY )
342 r = StgOpenStorage( szDBPath, NULL,
343 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
345 else if( szPersist == MSIDBOPEN_CREATE )
347 r = StgCreateDocfile( szDBPath,
348 STGM_CREATE|STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
350 if( SUCCEEDED(r) )
351 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
352 created = TRUE;
354 else if( szPersist == MSIDBOPEN_CREATEDIRECT )
356 r = StgCreateDocfile( szDBPath,
357 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
359 if( SUCCEEDED(r) )
360 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
361 created = TRUE;
363 else if( szPersist == MSIDBOPEN_TRANSACT )
365 r = StgOpenStorage( szDBPath, NULL,
366 STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
368 else if( szPersist == MSIDBOPEN_DIRECT )
370 r = StgOpenStorage( szDBPath, NULL,
371 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
373 else
375 ERR("unknown flag %p\n",szPersist);
376 return ERROR_INVALID_PARAMETER;
379 if( FAILED( r ) || !stg )
381 FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
382 return ERROR_FUNCTION_FAILED;
385 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
386 if( FAILED( r ) )
388 FIXME("Failed to stat storage\n");
389 goto end;
392 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
393 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
394 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
396 ERR("storage GUID is not a MSI database GUID %s\n",
397 debugstr_guid(&stat.clsid) );
398 goto end;
401 if ( patch && !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) )
403 ERR("storage GUID is not the MSI patch GUID %s\n",
404 debugstr_guid(&stat.clsid) );
405 ret = ERROR_OPEN_FAILED;
406 goto end;
409 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
410 MSI_CloseDatabase );
411 if( !db )
413 FIXME("Failed to allocate a handle\n");
414 goto end;
417 if (!strchrW( save_path, '\\' ))
419 GetCurrentDirectoryW( MAX_PATH, path );
420 lstrcatW( path, szBackSlash );
421 lstrcatW( path, save_path );
423 else
424 lstrcpyW( path, save_path );
426 db->path = strdupW( path );
427 db->media_transform_offset = MSI_INITIAL_MEDIA_TRANSFORM_OFFSET;
428 db->media_transform_disk_id = MSI_INITIAL_MEDIA_TRANSFORM_DISKID;
430 if( TRACE_ON( msi ) )
431 enum_stream_names( stg );
433 db->storage = stg;
434 db->mode = szMode;
435 if (created)
436 db->deletefile = strdupW( szDBPath );
437 list_init( &db->tables );
438 list_init( &db->transforms );
439 list_init( &db->streams );
441 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
442 if( !db->strings )
443 goto end;
445 ret = ERROR_SUCCESS;
447 msiobj_addref( &db->hdr );
448 IStorage_AddRef( stg );
449 *pdb = db;
451 end:
452 if( db )
453 msiobj_release( &db->hdr );
454 if( stg )
455 IStorage_Release( stg );
457 return ret;
460 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
462 MSIDATABASE *db;
463 UINT ret;
465 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
467 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
468 if( ret == ERROR_SUCCESS )
470 *phDB = alloc_msihandle( &db->hdr );
471 if (! *phDB)
472 ret = ERROR_NOT_ENOUGH_MEMORY;
473 msiobj_release( &db->hdr );
476 return ret;
479 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
481 HRESULT r = ERROR_FUNCTION_FAILED;
482 LPWSTR szwDBPath = NULL, szwPersist = NULL;
484 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
486 if( szDBPath )
488 szwDBPath = strdupAtoW( szDBPath );
489 if( !szwDBPath )
490 goto end;
493 if( !IS_INTMSIDBOPEN(szPersist) )
495 szwPersist = strdupAtoW( szPersist );
496 if( !szwPersist )
497 goto end;
499 else
500 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
502 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
504 end:
505 if( !IS_INTMSIDBOPEN(szPersist) )
506 msi_free( szwPersist );
507 msi_free( szwDBPath );
509 return r;
512 static LPWSTR msi_read_text_archive(LPCWSTR path, DWORD *len)
514 HANDLE file;
515 LPSTR data = NULL;
516 LPWSTR wdata = NULL;
517 DWORD read, size = 0;
519 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
520 if (file == INVALID_HANDLE_VALUE)
521 return NULL;
523 size = GetFileSize( file, NULL );
524 if (!(data = msi_alloc( size ))) goto done;
526 if (!ReadFile( file, data, size, &read, NULL ) || read != size) goto done;
528 while (!data[size - 1]) size--;
529 *len = MultiByteToWideChar( CP_ACP, 0, data, size, NULL, 0 );
530 if ((wdata = msi_alloc( (*len + 1) * sizeof(WCHAR) )))
532 MultiByteToWideChar( CP_ACP, 0, data, size, wdata, *len );
533 wdata[*len] = 0;
536 done:
537 CloseHandle( file );
538 msi_free( data );
539 return wdata;
542 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries, DWORD *len)
544 LPWSTR ptr = *line, save;
545 DWORD i, count = 1, chars_left = *len;
547 *entries = NULL;
549 /* stay on this line */
550 while (chars_left && *ptr != '\n')
552 /* entries are separated by tabs */
553 if (*ptr == '\t')
554 count++;
556 ptr++;
557 chars_left--;
560 *entries = msi_alloc(count * sizeof(LPWSTR));
561 if (!*entries)
562 return;
564 /* store pointers into the data */
565 chars_left = *len;
566 for (i = 0, ptr = *line; i < count; i++)
568 while (chars_left && *ptr == '\r')
570 ptr++;
571 chars_left--;
573 save = ptr;
575 while (chars_left && *ptr != '\t' && *ptr != '\n' && *ptr != '\r')
577 if (!*ptr) *ptr = '\n'; /* convert embedded nulls to \n */
578 ptr++;
579 chars_left--;
582 /* NULL-separate the data */
583 if (*ptr == '\n' || *ptr == '\r')
585 while (chars_left && (*ptr == '\n' || *ptr == '\r'))
587 *(ptr++) = 0;
588 chars_left--;
591 else if (*ptr)
593 *(ptr++) = 0;
594 chars_left--;
596 (*entries)[i] = save;
599 /* move to the next line if there's more, else EOF */
600 *line = ptr;
601 *len = chars_left;
602 if (num_entries)
603 *num_entries = count;
606 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
608 LPWSTR prelude;
609 DWORD size;
611 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
613 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
614 prelude = msi_alloc(size * sizeof(WCHAR));
615 if (!prelude)
616 return NULL;
618 sprintfW(prelude, create_fmt, table);
619 return prelude;
622 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
624 LPWSTR columns, p;
625 LPCWSTR type;
626 DWORD sql_size = 1, i, len;
627 WCHAR expanded[128], *ptr;
628 WCHAR size[10], comma[2], extra[30];
630 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
631 static const WCHAR size_fmt[] = {'(','%','s',')',0};
632 static const WCHAR type_char[] = {'C','H','A','R',0};
633 static const WCHAR type_int[] = {'I','N','T',0};
634 static const WCHAR type_long[] = {'L','O','N','G',0};
635 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
636 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
637 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
639 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
640 if (!columns)
641 return NULL;
643 for (i = 0; i < num_columns; i++)
645 type = NULL;
646 comma[1] = size[0] = extra[0] = '\0';
648 if (i == num_columns - 1)
649 comma[0] = '\0';
650 else
651 comma[0] = ',';
653 ptr = &types[i][1];
654 len = atolW(ptr);
655 extra[0] = '\0';
657 switch (types[i][0])
659 case 'l':
660 lstrcpyW(extra, type_notnull);
661 case 'L':
662 lstrcatW(extra, localizable);
663 type = type_char;
664 sprintfW(size, size_fmt, ptr);
665 break;
666 case 's':
667 lstrcpyW(extra, type_notnull);
668 case 'S':
669 type = type_char;
670 sprintfW(size, size_fmt, ptr);
671 break;
672 case 'i':
673 lstrcpyW(extra, type_notnull);
674 case 'I':
675 if (len <= 2)
676 type = type_int;
677 else if (len == 4)
678 type = type_long;
679 else
681 WARN("invalid int width %u\n", len);
682 msi_free(columns);
683 return NULL;
685 break;
686 case 'v':
687 lstrcpyW(extra, type_notnull);
688 case 'V':
689 type = type_object;
690 break;
691 default:
692 ERR("Unknown type: %c\n", types[i][0]);
693 msi_free(columns);
694 return NULL;
697 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
698 sql_size += lstrlenW(expanded);
700 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
701 if (!p)
703 msi_free(columns);
704 return NULL;
706 columns = p;
708 lstrcatW(columns, expanded);
711 return columns;
714 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
716 LPWSTR postlude, keys, ptr;
717 DWORD size, key_size, i;
719 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
720 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
722 for (i = 0, size = 1; i < num_keys; i++)
723 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
725 keys = msi_alloc(size * sizeof(WCHAR));
726 if (!keys)
727 return NULL;
729 for (i = 0, ptr = keys; i < num_keys; i++)
731 key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
732 sprintfW(ptr, key_fmt, primary_keys[i]);
733 ptr += key_size;
736 /* remove final ', ' */
737 *(ptr - 2) = '\0';
739 size = lstrlenW(postlude_fmt) + size - 1;
740 postlude = msi_alloc(size * sizeof(WCHAR));
741 if (!postlude)
742 goto done;
744 sprintfW(postlude, postlude_fmt, keys);
746 done:
747 msi_free(keys);
748 return postlude;
751 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
753 UINT r = ERROR_OUTOFMEMORY;
754 DWORD size;
755 MSIQUERY *view;
756 LPWSTR create_sql = NULL;
757 LPWSTR prelude, columns_sql, postlude;
759 prelude = msi_build_createsql_prelude(labels[0]);
760 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
761 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
763 if (!prelude || !columns_sql || !postlude)
764 goto done;
766 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
767 create_sql = msi_alloc(size * sizeof(WCHAR));
768 if (!create_sql)
769 goto done;
771 lstrcpyW(create_sql, prelude);
772 lstrcatW(create_sql, columns_sql);
773 lstrcatW(create_sql, postlude);
775 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
776 if (r != ERROR_SUCCESS)
777 goto done;
779 r = MSI_ViewExecute(view, NULL);
780 MSI_ViewClose(view);
781 msiobj_release(&view->hdr);
783 done:
784 msi_free(prelude);
785 msi_free(columns_sql);
786 msi_free(postlude);
787 msi_free(create_sql);
788 return r;
791 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
793 DWORD len;
794 LPWSTR fullname, ptr;
796 len = lstrlenW(path) + lstrlenW(name) + 1;
797 fullname = msi_alloc(len*sizeof(WCHAR));
798 if (!fullname)
799 return NULL;
801 lstrcpyW( fullname, path );
803 /* chop off extension from path */
804 ptr = strrchrW(fullname, '.');
805 if (!ptr)
807 msi_free (fullname);
808 return NULL;
810 *ptr++ = '\\';
811 lstrcpyW( ptr, name );
812 return fullname;
815 static UINT construct_record(DWORD num_columns, LPWSTR *types,
816 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
818 UINT i;
820 *rec = MSI_CreateRecord(num_columns);
821 if (!*rec)
822 return ERROR_OUTOFMEMORY;
824 for (i = 0; i < num_columns; i++)
826 switch (types[i][0])
828 case 'L': case 'l': case 'S': case 's':
829 MSI_RecordSetStringW(*rec, i + 1, data[i]);
830 break;
831 case 'I': case 'i':
832 if (*data[i])
833 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
834 break;
835 case 'V': case 'v':
836 if (*data[i])
838 UINT r;
839 LPWSTR file = msi_import_stream_filename(path, data[i]);
840 if (!file)
841 return ERROR_FUNCTION_FAILED;
843 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
844 msi_free (file);
845 if (r != ERROR_SUCCESS)
846 return ERROR_FUNCTION_FAILED;
848 break;
849 default:
850 ERR("Unhandled column type: %c\n", types[i][0]);
851 msiobj_release(&(*rec)->hdr);
852 return ERROR_FUNCTION_FAILED;
856 return ERROR_SUCCESS;
859 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
860 LPWSTR *labels, LPWSTR **records,
861 int num_columns, int num_records,
862 LPWSTR path)
864 UINT r;
865 int i;
866 MSIQUERY *view;
867 MSIRECORD *rec;
869 static const WCHAR select[] = {
870 'S','E','L','E','C','T',' ','*',' ',
871 'F','R','O','M',' ','`','%','s','`',0
874 r = MSI_OpenQuery(db, &view, select, labels[0]);
875 if (r != ERROR_SUCCESS)
876 return r;
878 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
880 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
881 msiobj_release(&rec->hdr);
882 if (r != ERROR_SUCCESS)
883 goto done;
886 for (i = 0; i < num_records; i++)
888 r = construct_record(num_columns, types, records[i], path, &rec);
889 if (r != ERROR_SUCCESS)
890 goto done;
892 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
893 if (r != ERROR_SUCCESS)
895 msiobj_release(&rec->hdr);
896 goto done;
899 msiobj_release(&rec->hdr);
902 done:
903 msiobj_release(&view->hdr);
904 return r;
907 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
909 UINT r;
910 DWORD len, i;
911 DWORD num_labels, num_types;
912 DWORD num_columns, num_records = 0;
913 LPWSTR *columns, *types, *labels;
914 LPWSTR path, ptr, data;
915 LPWSTR **records = NULL;
916 LPWSTR **temp_records;
918 static const WCHAR suminfo[] =
919 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
920 static const WCHAR forcecodepage[] =
921 {'_','F','o','r','c','e','C','o','d','e','p','a','g','e',0};
923 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
925 if( folder == NULL || file == NULL )
926 return ERROR_INVALID_PARAMETER;
928 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
929 path = msi_alloc( len * sizeof(WCHAR) );
930 if (!path)
931 return ERROR_OUTOFMEMORY;
933 lstrcpyW( path, folder );
934 lstrcatW( path, szBackSlash );
935 lstrcatW( path, file );
937 data = msi_read_text_archive( path, &len );
939 ptr = data;
940 msi_parse_line( &ptr, &columns, &num_columns, &len );
941 msi_parse_line( &ptr, &types, &num_types, &len );
942 msi_parse_line( &ptr, &labels, &num_labels, &len );
944 if (num_columns == 1 && !columns[0][0] && num_labels == 1 && !labels[0][0] &&
945 num_types == 2 && !strcmpW( types[1], forcecodepage ))
947 r = msi_set_string_table_codepage( db->strings, atoiW( types[0] ) );
948 goto done;
951 if (num_columns != num_types)
953 r = ERROR_FUNCTION_FAILED;
954 goto done;
957 records = msi_alloc(sizeof(LPWSTR *));
958 if (!records)
960 r = ERROR_OUTOFMEMORY;
961 goto done;
964 /* read in the table records */
965 while (len)
967 msi_parse_line( &ptr, &records[num_records], NULL, &len );
969 num_records++;
970 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
971 if (!temp_records)
973 r = ERROR_OUTOFMEMORY;
974 goto done;
976 records = temp_records;
979 if (!strcmpW(labels[0], suminfo))
981 r = msi_add_suminfo( db, records, num_records, num_columns );
982 if (r != ERROR_SUCCESS)
984 r = ERROR_FUNCTION_FAILED;
985 goto done;
988 else
990 if (!TABLE_Exists(db, labels[0]))
992 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
993 if (r != ERROR_SUCCESS)
995 r = ERROR_FUNCTION_FAILED;
996 goto done;
1000 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
1003 done:
1004 msi_free(path);
1005 msi_free(data);
1006 msi_free(columns);
1007 msi_free(types);
1008 msi_free(labels);
1010 for (i = 0; i < num_records; i++)
1011 msi_free(records[i]);
1013 msi_free(records);
1015 return r;
1018 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
1020 MSIDATABASE *db;
1021 UINT r;
1023 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
1025 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1026 if( !db )
1028 IWineMsiRemoteDatabase *remote_database;
1030 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1031 if ( !remote_database )
1032 return ERROR_INVALID_HANDLE;
1034 IWineMsiRemoteDatabase_Release( remote_database );
1035 WARN("MsiDatabaseImport not allowed during a custom action!\n");
1037 return ERROR_SUCCESS;
1040 r = MSI_DatabaseImport( db, szFolder, szFilename );
1041 msiobj_release( &db->hdr );
1042 return r;
1045 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
1046 LPCSTR szFolder, LPCSTR szFilename )
1048 LPWSTR path = NULL, file = NULL;
1049 UINT r = ERROR_OUTOFMEMORY;
1051 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
1053 if( szFolder )
1055 path = strdupAtoW( szFolder );
1056 if( !path )
1057 goto end;
1060 if( szFilename )
1062 file = strdupAtoW( szFilename );
1063 if( !file )
1064 goto end;
1067 r = MsiDatabaseImportW( handle, path, file );
1069 end:
1070 msi_free( path );
1071 msi_free( file );
1073 return r;
1076 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
1078 UINT i, count, len, r = ERROR_SUCCESS;
1079 const char *sep;
1080 char *buffer;
1081 DWORD sz;
1083 len = 0x100;
1084 buffer = msi_alloc( len );
1085 if ( !buffer )
1086 return ERROR_OUTOFMEMORY;
1088 count = MSI_RecordGetFieldCount( row );
1089 for ( i=start; i<=count; i++ )
1091 sz = len;
1092 r = MSI_RecordGetStringA( row, i, buffer, &sz );
1093 if (r == ERROR_MORE_DATA)
1095 char *p = msi_realloc( buffer, sz + 1 );
1096 if (!p)
1097 break;
1098 len = sz + 1;
1099 buffer = p;
1101 sz = len;
1102 r = MSI_RecordGetStringA( row, i, buffer, &sz );
1103 if (r != ERROR_SUCCESS)
1104 break;
1106 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
1108 r = ERROR_FUNCTION_FAILED;
1109 break;
1112 sep = (i < count) ? "\t" : "\r\n";
1113 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
1115 r = ERROR_FUNCTION_FAILED;
1116 break;
1119 msi_free( buffer );
1120 return r;
1123 static UINT msi_export_row( MSIRECORD *row, void *arg )
1125 return msi_export_record( arg, row, 1 );
1128 static UINT msi_export_forcecodepage( HANDLE handle, UINT codepage )
1130 static const char fmt[] = "\r\n\r\n%u\t_ForceCodepage\r\n";
1131 char data[sizeof(fmt) + 10];
1132 DWORD sz;
1134 sprintf( data, fmt, codepage );
1136 sz = lstrlenA(data) + 1;
1137 if (!WriteFile(handle, data, sz, &sz, NULL))
1138 return ERROR_FUNCTION_FAILED;
1140 return ERROR_SUCCESS;
1143 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
1144 LPCWSTR folder, LPCWSTR file )
1146 static const WCHAR query[] = {
1147 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
1148 static const WCHAR forcecodepage[] = {
1149 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
1150 MSIRECORD *rec = NULL;
1151 MSIQUERY *view = NULL;
1152 LPWSTR filename;
1153 HANDLE handle;
1154 UINT len, r;
1156 TRACE("%p %s %s %s\n", db, debugstr_w(table),
1157 debugstr_w(folder), debugstr_w(file) );
1159 if( folder == NULL || file == NULL )
1160 return ERROR_INVALID_PARAMETER;
1162 len = lstrlenW(folder) + lstrlenW(file) + 2;
1163 filename = msi_alloc(len * sizeof (WCHAR));
1164 if (!filename)
1165 return ERROR_OUTOFMEMORY;
1167 lstrcpyW( filename, folder );
1168 lstrcatW( filename, szBackSlash );
1169 lstrcatW( filename, file );
1171 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
1172 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
1173 msi_free( filename );
1174 if (handle == INVALID_HANDLE_VALUE)
1175 return ERROR_FUNCTION_FAILED;
1177 if (!strcmpW( table, forcecodepage ))
1179 UINT codepage = msi_get_string_table_codepage( db->strings );
1180 r = msi_export_forcecodepage( handle, codepage );
1181 goto done;
1184 r = MSI_OpenQuery( db, &view, query, table );
1185 if (r == ERROR_SUCCESS)
1187 /* write out row 1, the column names */
1188 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
1189 if (r == ERROR_SUCCESS)
1191 msi_export_record( handle, rec, 1 );
1192 msiobj_release( &rec->hdr );
1195 /* write out row 2, the column types */
1196 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
1197 if (r == ERROR_SUCCESS)
1199 msi_export_record( handle, rec, 1 );
1200 msiobj_release( &rec->hdr );
1203 /* write out row 3, the table name + keys */
1204 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
1205 if (r == ERROR_SUCCESS)
1207 MSI_RecordSetStringW( rec, 0, table );
1208 msi_export_record( handle, rec, 0 );
1209 msiobj_release( &rec->hdr );
1212 /* write out row 4 onwards, the data */
1213 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
1214 msiobj_release( &view->hdr );
1217 done:
1218 CloseHandle( handle );
1219 return r;
1222 /***********************************************************************
1223 * MsiExportDatabaseW [MSI.@]
1225 * Writes a file containing the table data as tab separated ASCII.
1227 * The format is as follows:
1229 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
1230 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
1231 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
1233 * Followed by the data, starting at row 1 with one row per line
1235 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
1237 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
1238 LPCWSTR szFolder, LPCWSTR szFilename )
1240 MSIDATABASE *db;
1241 UINT r;
1243 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
1244 debugstr_w(szFolder), debugstr_w(szFilename));
1246 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1247 if( !db )
1249 IWineMsiRemoteDatabase *remote_database;
1251 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1252 if ( !remote_database )
1253 return ERROR_INVALID_HANDLE;
1255 IWineMsiRemoteDatabase_Release( remote_database );
1256 WARN("MsiDatabaseExport not allowed during a custom action!\n");
1258 return ERROR_SUCCESS;
1261 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
1262 msiobj_release( &db->hdr );
1263 return r;
1266 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1267 LPCSTR szFolder, LPCSTR szFilename )
1269 LPWSTR path = NULL, file = NULL, table = NULL;
1270 UINT r = ERROR_OUTOFMEMORY;
1272 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1273 debugstr_a(szFolder), debugstr_a(szFilename));
1275 if( szTable )
1277 table = strdupAtoW( szTable );
1278 if( !table )
1279 goto end;
1282 if( szFolder )
1284 path = strdupAtoW( szFolder );
1285 if( !path )
1286 goto end;
1289 if( szFilename )
1291 file = strdupAtoW( szFilename );
1292 if( !file )
1293 goto end;
1296 r = MsiDatabaseExportW( handle, table, path, file );
1298 end:
1299 msi_free( table );
1300 msi_free( path );
1301 msi_free( file );
1303 return r;
1306 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1307 LPCSTR szTableName)
1309 UINT r;
1310 LPWSTR table;
1312 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1313 debugstr_a(szTableName));
1315 table = strdupAtoW(szTableName);
1316 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1318 msi_free(table);
1319 return r;
1322 typedef struct _tagMERGETABLE
1324 struct list entry;
1325 struct list rows;
1326 LPWSTR name;
1327 DWORD numconflicts;
1328 LPWSTR *columns;
1329 DWORD numcolumns;
1330 LPWSTR *types;
1331 DWORD numtypes;
1332 LPWSTR *labels;
1333 DWORD numlabels;
1334 } MERGETABLE;
1336 typedef struct _tagMERGEROW
1338 struct list entry;
1339 MSIRECORD *data;
1340 } MERGEROW;
1342 typedef struct _tagMERGEDATA
1344 MSIDATABASE *db;
1345 MSIDATABASE *merge;
1346 MERGETABLE *curtable;
1347 MSIQUERY *curview;
1348 struct list *tabledata;
1349 } MERGEDATA;
1351 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1353 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1354 ((type2[0] == 'l') || (type2[0] == 's')))
1355 return TRUE;
1357 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1358 ((type2[0] == 'L') || (type2[0] == 'S')))
1359 return TRUE;
1361 return !strcmpW( type1, type2 );
1364 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1366 MSIRECORD *dbrec, *mergerec;
1367 UINT r, i, count;
1369 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1370 if (r != ERROR_SUCCESS)
1371 return r;
1373 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1374 if (r != ERROR_SUCCESS)
1375 return r;
1377 count = MSI_RecordGetFieldCount(dbrec);
1378 for (i = 1; i <= count; i++)
1380 if (!MSI_RecordGetString(mergerec, i))
1381 break;
1383 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1385 r = ERROR_DATATYPE_MISMATCH;
1386 goto done;
1390 msiobj_release(&dbrec->hdr);
1391 msiobj_release(&mergerec->hdr);
1392 dbrec = mergerec = NULL;
1394 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1395 if (r != ERROR_SUCCESS)
1396 return r;
1398 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1399 if (r != ERROR_SUCCESS)
1400 return r;
1402 count = MSI_RecordGetFieldCount(dbrec);
1403 for (i = 1; i <= count; i++)
1405 if (!MSI_RecordGetString(mergerec, i))
1406 break;
1408 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1409 MSI_RecordGetString(mergerec, i)))
1411 r = ERROR_DATATYPE_MISMATCH;
1412 break;
1416 done:
1417 msiobj_release(&dbrec->hdr);
1418 msiobj_release(&mergerec->hdr);
1420 return r;
1423 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1424 LPCWSTR table)
1426 MSIRECORD *dbrec, *mergerec = NULL;
1427 UINT r, i, count;
1429 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1430 if (r != ERROR_SUCCESS)
1431 return r;
1433 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1434 if (r != ERROR_SUCCESS)
1435 goto done;
1437 count = MSI_RecordGetFieldCount(dbrec);
1438 if (count != MSI_RecordGetFieldCount(mergerec))
1440 r = ERROR_DATATYPE_MISMATCH;
1441 goto done;
1444 for (i = 1; i <= count; i++)
1446 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1448 r = ERROR_DATATYPE_MISMATCH;
1449 goto done;
1453 done:
1454 msiobj_release(&dbrec->hdr);
1455 msiobj_release(&mergerec->hdr);
1457 return r;
1460 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1462 MSIRECORD *colnames;
1463 LPWSTR str, val;
1464 UINT r, i = 0, sz = 0;
1465 int cmp;
1467 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1468 if (r != ERROR_SUCCESS)
1469 return NULL;
1473 str = msi_dup_record_field(colnames, ++i);
1474 cmp = strcmpW( key, str );
1475 msi_free(str);
1476 } while (cmp);
1478 msiobj_release(&colnames->hdr);
1480 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1481 if (r != ERROR_SUCCESS)
1482 return NULL;
1483 sz++;
1485 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1487 /* quote string record fields */
1488 const WCHAR szQuote[] = {'\'', 0};
1489 sz += 2;
1490 val = msi_alloc(sz*sizeof(WCHAR));
1491 if (!val)
1492 return NULL;
1494 lstrcpyW(val, szQuote);
1495 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1496 lstrcpyW(val+1+sz, szQuote);
1498 else
1500 /* do not quote integer record fields */
1501 val = msi_alloc(sz*sizeof(WCHAR));
1502 if (!val)
1503 return NULL;
1505 r = MSI_RecordGetStringW(rec, i, val, &sz);
1508 if (r != ERROR_SUCCESS)
1510 ERR("failed to get string!\n");
1511 msi_free(val);
1512 return NULL;
1515 return val;
1518 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1519 LPWSTR table, MSIRECORD *rec)
1521 LPWSTR query = NULL, clause = NULL;
1522 LPWSTR ptr = NULL, val;
1523 LPCWSTR setptr;
1524 DWORD size = 1, oldsize;
1525 LPCWSTR key;
1526 MSIRECORD *keys;
1527 UINT r, i, count;
1529 static const WCHAR keyset[] = {
1530 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1531 static const WCHAR lastkeyset[] = {
1532 '`','%','s','`',' ','=',' ','%','s',' ',0};
1533 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1534 'F','R','O','M',' ','`','%','s','`',' ',
1535 'W','H','E','R','E',' ','%','s',0};
1537 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1538 if (r != ERROR_SUCCESS)
1539 return NULL;
1541 clause = msi_alloc_zero(size * sizeof(WCHAR));
1542 if (!clause)
1543 goto done;
1545 ptr = clause;
1546 count = MSI_RecordGetFieldCount(keys);
1547 for (i = 1; i <= count; i++)
1549 key = MSI_RecordGetString(keys, i);
1550 val = get_key_value(view, key, rec);
1552 if (i == count)
1553 setptr = lastkeyset;
1554 else
1555 setptr = keyset;
1557 oldsize = size;
1558 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1559 clause = msi_realloc(clause, size * sizeof (WCHAR));
1560 if (!clause)
1562 msi_free(val);
1563 goto done;
1566 ptr = clause + oldsize - 1;
1567 sprintfW(ptr, setptr, key, val);
1568 msi_free(val);
1571 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1572 query = msi_alloc(size * sizeof(WCHAR));
1573 if (!query)
1574 goto done;
1576 sprintfW(query, fmt, table, clause);
1578 done:
1579 msi_free(clause);
1580 msiobj_release(&keys->hdr);
1581 return query;
1584 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1586 MERGEDATA *data = param;
1587 MERGETABLE *table = data->curtable;
1588 MERGEROW *mergerow;
1589 MSIQUERY *dbview = NULL;
1590 MSIRECORD *row = NULL;
1591 LPWSTR query = NULL;
1592 UINT r = ERROR_SUCCESS;
1594 if (TABLE_Exists(data->db, table->name))
1596 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1597 if (!query)
1598 return ERROR_OUTOFMEMORY;
1600 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1601 if (r != ERROR_SUCCESS)
1602 goto done;
1604 r = MSI_ViewExecute(dbview, NULL);
1605 if (r != ERROR_SUCCESS)
1606 goto done;
1608 r = MSI_ViewFetch(dbview, &row);
1609 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1611 table->numconflicts++;
1612 goto done;
1614 else if (r != ERROR_NO_MORE_ITEMS)
1615 goto done;
1617 r = ERROR_SUCCESS;
1620 mergerow = msi_alloc(sizeof(MERGEROW));
1621 if (!mergerow)
1623 r = ERROR_OUTOFMEMORY;
1624 goto done;
1627 mergerow->data = MSI_CloneRecord(rec);
1628 if (!mergerow->data)
1630 r = ERROR_OUTOFMEMORY;
1631 msi_free(mergerow);
1632 goto done;
1635 list_add_tail(&table->rows, &mergerow->entry);
1637 done:
1638 msi_free(query);
1639 msiobj_release(&row->hdr);
1640 msiobj_release(&dbview->hdr);
1641 return r;
1644 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1646 UINT r, i, count;
1647 MSIRECORD *prec = NULL;
1649 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1650 if (r != ERROR_SUCCESS)
1651 return r;
1653 count = MSI_RecordGetFieldCount(prec);
1654 *numlabels = count + 1;
1655 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1656 if (!*labels)
1658 r = ERROR_OUTOFMEMORY;
1659 goto end;
1662 (*labels)[0] = strdupW(table);
1663 for (i=1; i<=count; i++ )
1665 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1668 end:
1669 msiobj_release( &prec->hdr );
1670 return r;
1673 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1675 UINT r, i, count;
1676 MSIRECORD *prec = NULL;
1678 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1679 if (r != ERROR_SUCCESS)
1680 return r;
1682 count = MSI_RecordGetFieldCount(prec);
1683 *columns = msi_alloc(count*sizeof(LPWSTR));
1684 if (!*columns)
1686 r = ERROR_OUTOFMEMORY;
1687 goto end;
1690 for (i=1; i<=count; i++ )
1692 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1695 *numcolumns = count;
1697 end:
1698 msiobj_release( &prec->hdr );
1699 return r;
1702 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1704 UINT r, i, count;
1705 MSIRECORD *prec = NULL;
1707 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1708 if (r != ERROR_SUCCESS)
1709 return r;
1711 count = MSI_RecordGetFieldCount(prec);
1712 *types = msi_alloc(count*sizeof(LPWSTR));
1713 if (!*types)
1715 r = ERROR_OUTOFMEMORY;
1716 goto end;
1719 *numtypes = count;
1720 for (i=1; i<=count; i++ )
1722 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1725 end:
1726 msiobj_release( &prec->hdr );
1727 return r;
1730 static void merge_free_rows(MERGETABLE *table)
1732 struct list *item, *cursor;
1734 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1736 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1738 list_remove(&row->entry);
1739 msiobj_release(&row->data->hdr);
1740 msi_free(row);
1744 static void free_merge_table(MERGETABLE *table)
1746 UINT i;
1748 if (table->labels != NULL)
1750 for (i = 0; i < table->numlabels; i++)
1751 msi_free(table->labels[i]);
1753 msi_free(table->labels);
1756 if (table->columns != NULL)
1758 for (i = 0; i < table->numcolumns; i++)
1759 msi_free(table->columns[i]);
1761 msi_free(table->columns);
1764 if (table->types != NULL)
1766 for (i = 0; i < table->numtypes; i++)
1767 msi_free(table->types[i]);
1769 msi_free(table->types);
1772 msi_free(table->name);
1773 merge_free_rows(table);
1775 msi_free(table);
1778 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1780 UINT r;
1781 MERGETABLE *table;
1782 MSIQUERY *mergeview = NULL;
1784 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1785 'F','R','O','M',' ','`','%','s','`',0};
1787 table = msi_alloc_zero(sizeof(MERGETABLE));
1788 if (!table)
1790 *ptable = NULL;
1791 return ERROR_OUTOFMEMORY;
1794 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1795 if (r != ERROR_SUCCESS)
1796 goto err;
1798 r = MSI_OpenQuery(db, &mergeview, query, name);
1799 if (r != ERROR_SUCCESS)
1800 goto err;
1802 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1803 if (r != ERROR_SUCCESS)
1804 goto err;
1806 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1807 if (r != ERROR_SUCCESS)
1808 goto err;
1810 list_init(&table->rows);
1812 table->name = strdupW(name);
1813 table->numconflicts = 0;
1815 msiobj_release(&mergeview->hdr);
1816 *ptable = table;
1817 return ERROR_SUCCESS;
1819 err:
1820 msiobj_release(&mergeview->hdr);
1821 free_merge_table(table);
1822 *ptable = NULL;
1823 return r;
1826 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1828 MERGEDATA *data = param;
1829 MERGETABLE *table;
1830 MSIQUERY *dbview = NULL;
1831 MSIQUERY *mergeview = NULL;
1832 LPCWSTR name;
1833 UINT r;
1835 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1836 'F','R','O','M',' ','`','%','s','`',0};
1838 name = MSI_RecordGetString(rec, 1);
1840 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1841 if (r != ERROR_SUCCESS)
1842 goto done;
1844 if (TABLE_Exists(data->db, name))
1846 r = MSI_OpenQuery(data->db, &dbview, query, name);
1847 if (r != ERROR_SUCCESS)
1848 goto done;
1850 r = merge_verify_colnames(dbview, mergeview);
1851 if (r != ERROR_SUCCESS)
1852 goto done;
1854 r = merge_verify_primary_keys(data->db, data->merge, name);
1855 if (r != ERROR_SUCCESS)
1856 goto done;
1859 r = msi_get_merge_table(data->merge, name, &table);
1860 if (r != ERROR_SUCCESS)
1861 goto done;
1863 data->curtable = table;
1864 data->curview = mergeview;
1865 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1866 if (r != ERROR_SUCCESS)
1868 free_merge_table(table);
1869 goto done;
1872 list_add_tail(data->tabledata, &table->entry);
1874 done:
1875 msiobj_release(&dbview->hdr);
1876 msiobj_release(&mergeview->hdr);
1877 return r;
1880 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1881 struct list *tabledata)
1883 UINT r;
1884 MSIQUERY *view;
1885 MERGEDATA data;
1887 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1888 'F','R','O','M',' ','`','_','T','a','b','l','e','s','`',0};
1890 r = MSI_DatabaseOpenViewW(merge, query, &view);
1891 if (r != ERROR_SUCCESS)
1892 return r;
1894 data.db = db;
1895 data.merge = merge;
1896 data.tabledata = tabledata;
1897 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1899 msiobj_release(&view->hdr);
1900 return r;
1903 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1905 UINT r;
1906 MERGEROW *row;
1907 MSIVIEW *tv;
1909 if (!TABLE_Exists(db, table->name))
1911 r = msi_add_table_to_db(db, table->columns, table->types,
1912 table->labels, table->numlabels, table->numcolumns);
1913 if (r != ERROR_SUCCESS)
1914 return ERROR_FUNCTION_FAILED;
1917 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1919 r = TABLE_CreateView(db, table->name, &tv);
1920 if (r != ERROR_SUCCESS)
1921 return r;
1923 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1924 tv->ops->delete(tv);
1926 if (r != ERROR_SUCCESS)
1927 return r;
1930 return ERROR_SUCCESS;
1933 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1934 LPWSTR table, DWORD numconflicts)
1936 UINT r;
1937 MSIQUERY *view;
1939 static const WCHAR create[] = {
1940 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1941 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1942 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1943 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1944 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1945 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1946 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1947 static const WCHAR insert[] = {
1948 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1949 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1950 '`','N','u','m','R','o','w','M','e','r','g','e',
1951 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1952 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1954 if (!TABLE_Exists(db, error))
1956 r = MSI_OpenQuery(db, &view, create, error);
1957 if (r != ERROR_SUCCESS)
1958 return r;
1960 r = MSI_ViewExecute(view, NULL);
1961 msiobj_release(&view->hdr);
1962 if (r != ERROR_SUCCESS)
1963 return r;
1966 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1967 if (r != ERROR_SUCCESS)
1968 return r;
1970 r = MSI_ViewExecute(view, NULL);
1971 msiobj_release(&view->hdr);
1972 return r;
1975 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1976 LPCWSTR szTableName)
1978 struct list tabledata = LIST_INIT(tabledata);
1979 struct list *item, *cursor;
1980 MSIDATABASE *db, *merge;
1981 MERGETABLE *table;
1982 BOOL conflicts;
1983 UINT r;
1985 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1986 debugstr_w(szTableName));
1988 if (szTableName && !*szTableName)
1989 return ERROR_INVALID_TABLE;
1991 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1992 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1993 if (!db || !merge)
1995 r = ERROR_INVALID_HANDLE;
1996 goto done;
1999 r = gather_merge_data(db, merge, &tabledata);
2000 if (r != ERROR_SUCCESS)
2001 goto done;
2003 conflicts = FALSE;
2004 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
2006 if (table->numconflicts)
2008 conflicts = TRUE;
2010 r = update_merge_errors(db, szTableName, table->name,
2011 table->numconflicts);
2012 if (r != ERROR_SUCCESS)
2013 break;
2015 else
2017 r = merge_table(db, table);
2018 if (r != ERROR_SUCCESS)
2019 break;
2023 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
2025 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
2026 list_remove(&table->entry);
2027 free_merge_table(table);
2030 if (conflicts)
2031 r = ERROR_FUNCTION_FAILED;
2033 done:
2034 msiobj_release(&db->hdr);
2035 msiobj_release(&merge->hdr);
2036 return r;
2039 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
2041 MSIDBSTATE ret = MSIDBSTATE_READ;
2042 MSIDATABASE *db;
2044 TRACE("%d\n", handle);
2046 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
2047 if( !db )
2049 IWineMsiRemoteDatabase *remote_database;
2051 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
2052 if ( !remote_database )
2053 return MSIDBSTATE_ERROR;
2055 IWineMsiRemoteDatabase_Release( remote_database );
2056 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
2058 return MSIDBSTATE_READ;
2061 if (db->mode != MSIDBOPEN_READONLY )
2062 ret = MSIDBSTATE_WRITE;
2063 msiobj_release( &db->hdr );
2065 return ret;
2068 typedef struct _msi_remote_database_impl {
2069 IWineMsiRemoteDatabase IWineMsiRemoteDatabase_iface;
2070 MSIHANDLE database;
2071 LONG refs;
2072 } msi_remote_database_impl;
2074 static inline msi_remote_database_impl *impl_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase *iface )
2076 return CONTAINING_RECORD(iface, msi_remote_database_impl, IWineMsiRemoteDatabase_iface);
2079 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
2080 REFIID riid,LPVOID *ppobj)
2082 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
2083 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
2085 IUnknown_AddRef( iface );
2086 *ppobj = iface;
2087 return S_OK;
2090 return E_NOINTERFACE;
2093 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
2095 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
2097 return InterlockedIncrement( &This->refs );
2100 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
2102 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
2103 ULONG r;
2105 r = InterlockedDecrement( &This->refs );
2106 if (r == 0)
2108 MsiCloseHandle( This->database );
2109 msi_free( This );
2111 return r;
2114 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
2115 LPCWSTR table, MSICONDITION *persistent )
2117 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
2118 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
2119 return S_OK;
2122 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
2123 LPCWSTR table, MSIHANDLE *keys )
2125 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
2126 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
2127 return HRESULT_FROM_WIN32(r);
2130 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
2131 UINT updatecount, MSIHANDLE *suminfo )
2133 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
2134 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
2135 return HRESULT_FROM_WIN32(r);
2138 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
2139 LPCWSTR query, MSIHANDLE *view )
2141 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
2142 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
2143 return HRESULT_FROM_WIN32(r);
2146 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
2148 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
2149 This->database = handle;
2150 return S_OK;
2153 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
2155 mrd_QueryInterface,
2156 mrd_AddRef,
2157 mrd_Release,
2158 mrd_IsTablePersistent,
2159 mrd_GetPrimaryKeys,
2160 mrd_GetSummaryInformation,
2161 mrd_OpenView,
2162 mrd_SetMsiHandle,
2165 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
2167 msi_remote_database_impl *This;
2169 This = msi_alloc( sizeof *This );
2170 if (!This)
2171 return E_OUTOFMEMORY;
2173 This->IWineMsiRemoteDatabase_iface.lpVtbl = &msi_remote_database_vtbl;
2174 This->database = 0;
2175 This->refs = 1;
2177 *ppObj = This;
2179 return S_OK;