shlwapi/tests: Run more language dependent tests only on English locales.
[wine.git] / dlls / msi / database.c
blob01c32497a37b03cf381fa3a6c1c8061c7befb49d
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>
23 #define COBJMACROS
24 #define NONAMELESSUNION
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winreg.h"
29 #include "winnls.h"
30 #include "wine/debug.h"
31 #include "wine/unicode.h"
32 #include "msi.h"
33 #include "msiquery.h"
34 #include "msipriv.h"
35 #include "objidl.h"
36 #include "objbase.h"
37 #include "msiserver.h"
38 #include "query.h"
40 #include "initguid.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(msi);
45 * .MSI file format
47 * An .msi file is a structured storage file.
48 * It contains a number of streams.
49 * A stream for each table in the database.
50 * Two streams for the string table in the database.
51 * Any binary data in a table is a reference to a stream.
54 #define IS_INTMSIDBOPEN(x) (((ULONG_PTR)(x) >> 16) == 0)
56 typedef struct tagMSITRANSFORM {
57 struct list entry;
58 IStorage *stg;
59 } MSITRANSFORM;
61 typedef struct tagMSISTREAM {
62 struct list entry;
63 IStream *stm;
64 } MSISTREAM;
66 static UINT find_open_stream( MSIDATABASE *db, LPCWSTR name, IStream **stm )
68 MSISTREAM *stream;
70 LIST_FOR_EACH_ENTRY( stream, &db->streams, MSISTREAM, entry )
72 HRESULT r;
73 STATSTG stat;
75 r = IStream_Stat( stream->stm, &stat, 0 );
76 if( FAILED( r ) )
78 WARN("failed to stat stream r = %08x!\n", r);
79 continue;
82 if( !lstrcmpW( name, stat.pwcsName ) )
84 TRACE("found %s\n", debugstr_w(name));
85 *stm = stream->stm;
86 CoTaskMemFree( stat.pwcsName );
87 return ERROR_SUCCESS;
90 CoTaskMemFree( stat.pwcsName );
93 return ERROR_FUNCTION_FAILED;
96 static UINT clone_open_stream( MSIDATABASE *db, LPCWSTR name, IStream **stm )
98 IStream *stream;
100 if (find_open_stream( db, name, &stream ) == ERROR_SUCCESS)
102 HRESULT r;
103 LARGE_INTEGER pos;
105 r = IStream_Clone( stream, stm );
106 if( FAILED( r ) )
108 WARN("failed to clone stream r = %08x!\n", r);
109 return ERROR_FUNCTION_FAILED;
112 pos.QuadPart = 0;
113 r = IStream_Seek( *stm, pos, STREAM_SEEK_SET, NULL );
114 if( FAILED( r ) )
116 IStream_Release( *stm );
117 return ERROR_FUNCTION_FAILED;
120 return ERROR_SUCCESS;
123 return ERROR_FUNCTION_FAILED;
126 UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
128 HRESULT r;
129 WCHAR decoded[MAX_STREAM_NAME_LEN];
131 decode_streamname( stname, decoded );
132 TRACE("%s -> %s\n", debugstr_w(stname), debugstr_w(decoded));
134 if (clone_open_stream( db, stname, stm ) == ERROR_SUCCESS)
135 return ERROR_SUCCESS;
137 r = IStorage_OpenStream( db->storage, stname, NULL,
138 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
139 if( FAILED( r ) )
141 MSITRANSFORM *transform;
143 LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
145 r = IStorage_OpenStream( transform->stg, stname, NULL,
146 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
147 if (SUCCEEDED(r))
148 break;
152 if( SUCCEEDED(r) )
154 MSISTREAM *stream;
156 stream = msi_alloc( sizeof(MSISTREAM) );
157 if( !stream )
158 return ERROR_NOT_ENOUGH_MEMORY;
160 stream->stm = *stm;
161 IStream_AddRef( *stm );
162 list_add_tail( &db->streams, &stream->entry );
165 return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
168 static void free_transforms( MSIDATABASE *db )
170 while( !list_empty( &db->transforms ) )
172 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
173 MSITRANSFORM, entry );
174 list_remove( &t->entry );
175 IStorage_Release( t->stg );
176 msi_free( t );
180 void db_destroy_stream( MSIDATABASE *db, LPCWSTR stname )
182 MSISTREAM *stream, *stream2;
184 LIST_FOR_EACH_ENTRY_SAFE( stream, stream2, &db->streams, MSISTREAM, entry )
186 HRESULT r;
187 STATSTG stat;
189 r = IStream_Stat( stream->stm, &stat, 0 );
190 if (FAILED(r))
192 WARN("failed to stat stream r = %08x\n", r);
193 continue;
196 if (!strcmpW( stname, stat.pwcsName ))
198 TRACE("destroying %s\n", debugstr_w(stname));
200 list_remove( &stream->entry );
201 IStream_Release( stream->stm );
202 msi_free( stream );
203 IStorage_DestroyElement( db->storage, stname );
204 CoTaskMemFree( stat.pwcsName );
205 break;
207 CoTaskMemFree( stat.pwcsName );
211 static void free_streams( MSIDATABASE *db )
213 while( !list_empty( &db->streams ) )
215 MSISTREAM *s = LIST_ENTRY( list_head( &db->streams ),
216 MSISTREAM, entry );
217 list_remove( &s->entry );
218 IStream_Release( s->stm );
219 msi_free( s );
223 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
225 MSITRANSFORM *t;
227 t = msi_alloc( sizeof *t );
228 t->stg = stg;
229 IStorage_AddRef( stg );
230 list_add_head( &db->transforms, &t->entry );
232 /* the transform may add or replace streams */
233 free_streams( db );
236 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
238 MSIDATABASE *db = (MSIDATABASE *) arg;
240 msi_free(db->path);
241 free_cached_tables( db );
242 free_streams( db );
243 free_transforms( db );
244 msi_destroy_stringtable( db->strings );
245 IStorage_Release( db->storage );
246 if (db->deletefile)
248 DeleteFileW( db->deletefile );
249 msi_free( db->deletefile );
251 if (db->localfile)
253 DeleteFileW( db->localfile );
254 msi_free( db->localfile );
258 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
260 IStorage *stg = NULL;
261 HRESULT r;
262 MSIDATABASE *db = NULL;
263 UINT ret = ERROR_FUNCTION_FAILED;
264 LPCWSTR szMode, save_path;
265 STATSTG stat;
266 BOOL created = FALSE, patch = FALSE;
267 WCHAR path[MAX_PATH];
269 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
271 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
273 if( !pdb )
274 return ERROR_INVALID_PARAMETER;
276 if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
277 szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
279 TRACE("Database is a patch\n");
280 szPersist -= MSIDBOPEN_PATCHFILE;
281 patch = TRUE;
284 save_path = szDBPath;
285 szMode = szPersist;
286 if( !IS_INTMSIDBOPEN(szPersist) )
288 if (!CopyFileW( szDBPath, szPersist, FALSE ))
289 return ERROR_OPEN_FAILED;
291 szDBPath = szPersist;
292 szPersist = MSIDBOPEN_TRANSACT;
293 created = TRUE;
296 if( szPersist == MSIDBOPEN_READONLY )
298 r = StgOpenStorage( szDBPath, NULL,
299 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
301 else if( szPersist == MSIDBOPEN_CREATE || szPersist == MSIDBOPEN_CREATEDIRECT )
303 /* FIXME: MSIDBOPEN_CREATE should case STGM_TRANSACTED flag to be
304 * used here: */
305 r = StgCreateDocfile( szDBPath,
306 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg);
307 if( r == ERROR_SUCCESS )
309 IStorage_SetClass( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
310 /* create the _Tables stream */
311 r = write_stream_data(stg, szTables, NULL, 0, TRUE);
312 if (SUCCEEDED(r))
313 r = msi_init_string_table( stg );
315 created = TRUE;
317 else if( szPersist == MSIDBOPEN_TRANSACT )
319 /* FIXME: MSIDBOPEN_TRANSACT should case STGM_TRANSACTED flag to be
320 * used here: */
321 r = StgOpenStorage( szDBPath, NULL,
322 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
324 else if( szPersist == MSIDBOPEN_DIRECT )
326 r = StgOpenStorage( szDBPath, NULL,
327 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
329 else
331 ERR("unknown flag %p\n",szPersist);
332 return ERROR_INVALID_PARAMETER;
335 if( FAILED( r ) || !stg )
337 FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
338 return ERROR_FUNCTION_FAILED;
341 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
342 if( FAILED( r ) )
344 FIXME("Failed to stat storage\n");
345 goto end;
348 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
349 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
350 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
352 ERR("storage GUID is not a MSI database GUID %s\n",
353 debugstr_guid(&stat.clsid) );
354 goto end;
357 if ( patch && !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) )
359 ERR("storage GUID is not the MSI patch GUID %s\n",
360 debugstr_guid(&stat.clsid) );
361 ret = ERROR_OPEN_FAILED;
362 goto end;
365 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
366 MSI_CloseDatabase );
367 if( !db )
369 FIXME("Failed to allocate a handle\n");
370 goto end;
373 if (!strchrW( save_path, '\\' ))
375 GetCurrentDirectoryW( MAX_PATH, path );
376 lstrcatW( path, szBackSlash );
377 lstrcatW( path, save_path );
379 else
380 lstrcpyW( path, save_path );
382 db->path = strdupW( path );
384 if( TRACE_ON( msi ) )
385 enum_stream_names( stg );
387 db->storage = stg;
388 db->mode = szMode;
389 if (created)
390 db->deletefile = strdupW( szDBPath );
391 list_init( &db->tables );
392 list_init( &db->transforms );
393 list_init( &db->streams );
395 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
396 if( !db->strings )
397 goto end;
399 ret = ERROR_SUCCESS;
401 msiobj_addref( &db->hdr );
402 IStorage_AddRef( stg );
403 *pdb = db;
405 end:
406 if( db )
407 msiobj_release( &db->hdr );
408 if( stg )
409 IStorage_Release( stg );
411 return ret;
414 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
416 MSIDATABASE *db;
417 UINT ret;
419 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
421 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
422 if( ret == ERROR_SUCCESS )
424 *phDB = alloc_msihandle( &db->hdr );
425 if (! *phDB)
426 ret = ERROR_NOT_ENOUGH_MEMORY;
427 msiobj_release( &db->hdr );
430 return ret;
433 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
435 HRESULT r = ERROR_FUNCTION_FAILED;
436 LPWSTR szwDBPath = NULL, szwPersist = NULL;
438 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
440 if( szDBPath )
442 szwDBPath = strdupAtoW( szDBPath );
443 if( !szwDBPath )
444 goto end;
447 if( !IS_INTMSIDBOPEN(szPersist) )
449 szwPersist = strdupAtoW( szPersist );
450 if( !szwPersist )
451 goto end;
453 else
454 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
456 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
458 end:
459 if( !IS_INTMSIDBOPEN(szPersist) )
460 msi_free( szwPersist );
461 msi_free( szwDBPath );
463 return r;
466 static LPWSTR msi_read_text_archive(LPCWSTR path)
468 HANDLE file;
469 LPSTR data = NULL;
470 LPWSTR wdata = NULL;
471 DWORD read, size = 0;
473 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
474 if (file == INVALID_HANDLE_VALUE)
475 return NULL;
477 size = GetFileSize( file, NULL );
478 data = msi_alloc( size + 1 );
479 if (!data)
480 goto done;
482 if (!ReadFile( file, data, size, &read, NULL ))
483 goto done;
485 data[size] = '\0';
486 wdata = strdupAtoW( data );
488 done:
489 CloseHandle( file );
490 msi_free( data );
491 return wdata;
494 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
496 LPWSTR ptr = *line, save;
497 DWORD i, count = 1;
499 *entries = NULL;
501 /* stay on this line */
502 while (*ptr && *ptr != '\n')
504 /* entries are separated by tabs */
505 if (*ptr == '\t')
506 count++;
508 ptr++;
511 *entries = msi_alloc(count * sizeof(LPWSTR));
512 if (!*entries)
513 return;
515 /* store pointers into the data */
516 for (i = 0, ptr = *line; i < count; i++)
518 while (*ptr && *ptr == '\r') ptr++;
519 save = ptr;
521 while (*ptr && *ptr != '\t' && *ptr != '\n' && *ptr != '\r') ptr++;
523 /* NULL-separate the data */
524 if (*ptr == '\n' || *ptr == '\r')
526 while (*ptr == '\n' || *ptr == '\r')
527 *(ptr++) = '\0';
529 else if (*ptr)
530 *ptr++ = '\0';
532 (*entries)[i] = save;
535 /* move to the next line if there's more, else EOF */
536 *line = ptr;
538 if (num_entries)
539 *num_entries = count;
542 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
544 LPWSTR prelude;
545 DWORD size;
547 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
549 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
550 prelude = msi_alloc(size * sizeof(WCHAR));
551 if (!prelude)
552 return NULL;
554 sprintfW(prelude, create_fmt, table);
555 return prelude;
558 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
560 LPWSTR columns, p;
561 LPCWSTR type;
562 DWORD sql_size = 1, i, len;
563 WCHAR expanded[128], *ptr;
564 WCHAR size[10], comma[2], extra[30];
566 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
567 static const WCHAR size_fmt[] = {'(','%','s',')',0};
568 static const WCHAR type_char[] = {'C','H','A','R',0};
569 static const WCHAR type_int[] = {'I','N','T',0};
570 static const WCHAR type_long[] = {'L','O','N','G',0};
571 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
572 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
573 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
575 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
576 if (!columns)
577 return NULL;
579 for (i = 0; i < num_columns; i++)
581 type = NULL;
582 comma[1] = size[0] = extra[0] = '\0';
584 if (i == num_columns - 1)
585 comma[0] = '\0';
586 else
587 comma[0] = ',';
589 ptr = &types[i][1];
590 len = atolW(ptr);
591 extra[0] = '\0';
593 switch (types[i][0])
595 case 'l':
596 lstrcpyW(extra, type_notnull);
597 case 'L':
598 lstrcatW(extra, localizable);
599 type = type_char;
600 sprintfW(size, size_fmt, ptr);
601 break;
602 case 's':
603 lstrcpyW(extra, type_notnull);
604 case 'S':
605 type = type_char;
606 sprintfW(size, size_fmt, ptr);
607 break;
608 case 'i':
609 lstrcpyW(extra, type_notnull);
610 case 'I':
611 if (len <= 2)
612 type = type_int;
613 else if (len == 4)
614 type = type_long;
615 else
617 WARN("invalid int width %u\n", len);
618 msi_free(columns);
619 return NULL;
621 break;
622 case 'v':
623 lstrcpyW(extra, type_notnull);
624 case 'V':
625 type = type_object;
626 break;
627 default:
628 ERR("Unknown type: %c\n", types[i][0]);
629 msi_free(columns);
630 return NULL;
633 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
634 sql_size += lstrlenW(expanded);
636 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
637 if (!p)
639 msi_free(columns);
640 return NULL;
642 columns = p;
644 lstrcatW(columns, expanded);
647 return columns;
650 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
652 LPWSTR postlude, keys, ptr;
653 DWORD size, key_size, i;
655 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
656 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
658 for (i = 0, size = 1; i < num_keys; i++)
659 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
661 keys = msi_alloc(size * sizeof(WCHAR));
662 if (!keys)
663 return NULL;
665 for (i = 0, ptr = keys; i < num_keys; i++)
667 key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
668 sprintfW(ptr, key_fmt, primary_keys[i]);
669 ptr += key_size;
672 /* remove final ', ' */
673 *(ptr - 2) = '\0';
675 size = lstrlenW(postlude_fmt) + size - 1;
676 postlude = msi_alloc(size * sizeof(WCHAR));
677 if (!postlude)
678 goto done;
680 sprintfW(postlude, postlude_fmt, keys);
682 done:
683 msi_free(keys);
684 return postlude;
687 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
689 UINT r = ERROR_OUTOFMEMORY;
690 DWORD size;
691 MSIQUERY *view;
692 LPWSTR create_sql = NULL;
693 LPWSTR prelude, columns_sql, postlude;
695 prelude = msi_build_createsql_prelude(labels[0]);
696 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
697 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
699 if (!prelude || !columns_sql || !postlude)
700 goto done;
702 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
703 create_sql = msi_alloc(size * sizeof(WCHAR));
704 if (!create_sql)
705 goto done;
707 lstrcpyW(create_sql, prelude);
708 lstrcatW(create_sql, columns_sql);
709 lstrcatW(create_sql, postlude);
711 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
712 if (r != ERROR_SUCCESS)
713 goto done;
715 r = MSI_ViewExecute(view, NULL);
716 MSI_ViewClose(view);
717 msiobj_release(&view->hdr);
719 done:
720 msi_free(prelude);
721 msi_free(columns_sql);
722 msi_free(postlude);
723 msi_free(create_sql);
724 return r;
727 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
729 DWORD len;
730 LPWSTR fullname, ptr;
732 len = lstrlenW(path) + lstrlenW(name) + 1;
733 fullname = msi_alloc(len*sizeof(WCHAR));
734 if (!fullname)
735 return NULL;
737 lstrcpyW( fullname, path );
739 /* chop off extension from path */
740 ptr = strrchrW(fullname, '.');
741 if (!ptr)
743 msi_free (fullname);
744 return NULL;
746 *ptr++ = '\\';
747 lstrcpyW( ptr, name );
748 return fullname;
751 static UINT construct_record(DWORD num_columns, LPWSTR *types,
752 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
754 UINT i;
756 *rec = MSI_CreateRecord(num_columns);
757 if (!*rec)
758 return ERROR_OUTOFMEMORY;
760 for (i = 0; i < num_columns; i++)
762 switch (types[i][0])
764 case 'L': case 'l': case 'S': case 's':
765 MSI_RecordSetStringW(*rec, i + 1, data[i]);
766 break;
767 case 'I': case 'i':
768 if (*data[i])
769 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
770 break;
771 case 'V': case 'v':
772 if (*data[i])
774 UINT r;
775 LPWSTR file = msi_import_stream_filename(path, data[i]);
776 if (!file)
777 return ERROR_FUNCTION_FAILED;
779 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
780 msi_free (file);
781 if (r != ERROR_SUCCESS)
782 return ERROR_FUNCTION_FAILED;
784 break;
785 default:
786 ERR("Unhandled column type: %c\n", types[i][0]);
787 msiobj_release(&(*rec)->hdr);
788 return ERROR_FUNCTION_FAILED;
792 return ERROR_SUCCESS;
795 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
796 LPWSTR *labels, LPWSTR **records,
797 int num_columns, int num_records,
798 LPWSTR path)
800 UINT r;
801 int i;
802 MSIQUERY *view;
803 MSIRECORD *rec;
805 static const WCHAR select[] = {
806 'S','E','L','E','C','T',' ','*',' ',
807 'F','R','O','M',' ','`','%','s','`',0
810 r = MSI_OpenQuery(db, &view, select, labels[0]);
811 if (r != ERROR_SUCCESS)
812 return r;
814 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
816 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
817 msiobj_release(&rec->hdr);
818 if (r != ERROR_SUCCESS)
819 goto done;
822 for (i = 0; i < num_records; i++)
824 r = construct_record(num_columns, types, records[i], path, &rec);
825 if (r != ERROR_SUCCESS)
826 goto done;
828 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
829 if (r != ERROR_SUCCESS)
831 msiobj_release(&rec->hdr);
832 goto done;
835 msiobj_release(&rec->hdr);
838 done:
839 msiobj_release(&view->hdr);
840 return r;
843 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
845 UINT r;
846 DWORD len, i;
847 DWORD num_labels, num_types;
848 DWORD num_columns, num_records = 0;
849 LPWSTR *columns, *types, *labels;
850 LPWSTR path, ptr, data;
851 LPWSTR **records = NULL;
852 LPWSTR **temp_records;
854 static const WCHAR suminfo[] =
855 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
857 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
859 if( folder == NULL || file == NULL )
860 return ERROR_INVALID_PARAMETER;
862 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
863 path = msi_alloc( len * sizeof(WCHAR) );
864 if (!path)
865 return ERROR_OUTOFMEMORY;
867 lstrcpyW( path, folder );
868 lstrcatW( path, szBackSlash );
869 lstrcatW( path, file );
871 data = msi_read_text_archive( path );
873 ptr = data;
874 msi_parse_line( &ptr, &columns, &num_columns );
875 msi_parse_line( &ptr, &types, &num_types );
876 msi_parse_line( &ptr, &labels, &num_labels );
878 if (num_columns != num_types)
880 r = ERROR_FUNCTION_FAILED;
881 goto done;
884 records = msi_alloc(sizeof(LPWSTR *));
885 if (!records)
887 r = ERROR_OUTOFMEMORY;
888 goto done;
891 /* read in the table records */
892 while (*ptr)
894 msi_parse_line( &ptr, &records[num_records], NULL );
896 num_records++;
897 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
898 if (!temp_records)
900 r = ERROR_OUTOFMEMORY;
901 goto done;
903 records = temp_records;
906 if (!strcmpW(labels[0], suminfo))
908 r = msi_add_suminfo( db, records, num_records, num_columns );
909 if (r != ERROR_SUCCESS)
911 r = ERROR_FUNCTION_FAILED;
912 goto done;
915 else
917 if (!TABLE_Exists(db, labels[0]))
919 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
920 if (r != ERROR_SUCCESS)
922 r = ERROR_FUNCTION_FAILED;
923 goto done;
927 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
930 done:
931 msi_free(path);
932 msi_free(data);
933 msi_free(columns);
934 msi_free(types);
935 msi_free(labels);
937 for (i = 0; i < num_records; i++)
938 msi_free(records[i]);
940 msi_free(records);
942 return r;
945 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
947 MSIDATABASE *db;
948 UINT r;
950 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
952 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
953 if( !db )
955 IWineMsiRemoteDatabase *remote_database;
957 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
958 if ( !remote_database )
959 return ERROR_INVALID_HANDLE;
961 IWineMsiRemoteDatabase_Release( remote_database );
962 WARN("MsiDatabaseImport not allowed during a custom action!\n");
964 return ERROR_SUCCESS;
967 r = MSI_DatabaseImport( db, szFolder, szFilename );
968 msiobj_release( &db->hdr );
969 return r;
972 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
973 LPCSTR szFolder, LPCSTR szFilename )
975 LPWSTR path = NULL, file = NULL;
976 UINT r = ERROR_OUTOFMEMORY;
978 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
980 if( szFolder )
982 path = strdupAtoW( szFolder );
983 if( !path )
984 goto end;
987 if( szFilename )
989 file = strdupAtoW( szFilename );
990 if( !file )
991 goto end;
994 r = MsiDatabaseImportW( handle, path, file );
996 end:
997 msi_free( path );
998 msi_free( file );
1000 return r;
1003 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
1005 UINT i, count, len, r = ERROR_SUCCESS;
1006 const char *sep;
1007 char *buffer;
1008 DWORD sz;
1010 len = 0x100;
1011 buffer = msi_alloc( len );
1012 if ( !buffer )
1013 return ERROR_OUTOFMEMORY;
1015 count = MSI_RecordGetFieldCount( row );
1016 for ( i=start; i<=count; i++ )
1018 sz = len;
1019 r = MSI_RecordGetStringA( row, i, buffer, &sz );
1020 if (r == ERROR_MORE_DATA)
1022 char *p = msi_realloc( buffer, sz + 1 );
1023 if (!p)
1024 break;
1025 len = sz + 1;
1026 buffer = p;
1028 sz = len;
1029 r = MSI_RecordGetStringA( row, i, buffer, &sz );
1030 if (r != ERROR_SUCCESS)
1031 break;
1033 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
1035 r = ERROR_FUNCTION_FAILED;
1036 break;
1039 sep = (i < count) ? "\t" : "\r\n";
1040 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
1042 r = ERROR_FUNCTION_FAILED;
1043 break;
1046 msi_free( buffer );
1047 return r;
1050 static UINT msi_export_row( MSIRECORD *row, void *arg )
1052 return msi_export_record( arg, row, 1 );
1055 static UINT msi_export_forcecodepage( HANDLE handle )
1057 DWORD sz;
1059 static const char data[] = "\r\n\r\n0\t_ForceCodepage\r\n";
1061 FIXME("Read the codepage from the strings table!\n");
1063 sz = lstrlenA(data) + 1;
1064 if (!WriteFile(handle, data, sz, &sz, NULL))
1065 return ERROR_FUNCTION_FAILED;
1067 return ERROR_SUCCESS;
1070 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
1071 LPCWSTR folder, LPCWSTR file )
1073 static const WCHAR query[] = {
1074 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
1075 static const WCHAR forcecodepage[] = {
1076 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
1077 MSIRECORD *rec = NULL;
1078 MSIQUERY *view = NULL;
1079 LPWSTR filename;
1080 HANDLE handle;
1081 UINT len, r;
1083 TRACE("%p %s %s %s\n", db, debugstr_w(table),
1084 debugstr_w(folder), debugstr_w(file) );
1086 if( folder == NULL || file == NULL )
1087 return ERROR_INVALID_PARAMETER;
1089 len = lstrlenW(folder) + lstrlenW(file) + 2;
1090 filename = msi_alloc(len * sizeof (WCHAR));
1091 if (!filename)
1092 return ERROR_OUTOFMEMORY;
1094 lstrcpyW( filename, folder );
1095 lstrcatW( filename, szBackSlash );
1096 lstrcatW( filename, file );
1098 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
1099 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
1100 msi_free( filename );
1101 if (handle == INVALID_HANDLE_VALUE)
1102 return ERROR_FUNCTION_FAILED;
1104 if (!lstrcmpW( table, forcecodepage ))
1106 r = msi_export_forcecodepage( handle );
1107 goto done;
1110 r = MSI_OpenQuery( db, &view, query, table );
1111 if (r == ERROR_SUCCESS)
1113 /* write out row 1, the column names */
1114 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
1115 if (r == ERROR_SUCCESS)
1117 msi_export_record( handle, rec, 1 );
1118 msiobj_release( &rec->hdr );
1121 /* write out row 2, the column types */
1122 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
1123 if (r == ERROR_SUCCESS)
1125 msi_export_record( handle, rec, 1 );
1126 msiobj_release( &rec->hdr );
1129 /* write out row 3, the table name + keys */
1130 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
1131 if (r == ERROR_SUCCESS)
1133 MSI_RecordSetStringW( rec, 0, table );
1134 msi_export_record( handle, rec, 0 );
1135 msiobj_release( &rec->hdr );
1138 /* write out row 4 onwards, the data */
1139 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
1140 msiobj_release( &view->hdr );
1143 done:
1144 CloseHandle( handle );
1145 return r;
1148 /***********************************************************************
1149 * MsiExportDatabaseW [MSI.@]
1151 * Writes a file containing the table data as tab separated ASCII.
1153 * The format is as follows:
1155 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
1156 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
1157 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
1159 * Followed by the data, starting at row 1 with one row per line
1161 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
1163 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
1164 LPCWSTR szFolder, LPCWSTR szFilename )
1166 MSIDATABASE *db;
1167 UINT r;
1169 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
1170 debugstr_w(szFolder), debugstr_w(szFilename));
1172 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1173 if( !db )
1175 IWineMsiRemoteDatabase *remote_database;
1177 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1178 if ( !remote_database )
1179 return ERROR_INVALID_HANDLE;
1181 IWineMsiRemoteDatabase_Release( remote_database );
1182 WARN("MsiDatabaseExport not allowed during a custom action!\n");
1184 return ERROR_SUCCESS;
1187 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
1188 msiobj_release( &db->hdr );
1189 return r;
1192 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1193 LPCSTR szFolder, LPCSTR szFilename )
1195 LPWSTR path = NULL, file = NULL, table = NULL;
1196 UINT r = ERROR_OUTOFMEMORY;
1198 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1199 debugstr_a(szFolder), debugstr_a(szFilename));
1201 if( szTable )
1203 table = strdupAtoW( szTable );
1204 if( !table )
1205 goto end;
1208 if( szFolder )
1210 path = strdupAtoW( szFolder );
1211 if( !path )
1212 goto end;
1215 if( szFilename )
1217 file = strdupAtoW( szFilename );
1218 if( !file )
1219 goto end;
1222 r = MsiDatabaseExportW( handle, table, path, file );
1224 end:
1225 msi_free( table );
1226 msi_free( path );
1227 msi_free( file );
1229 return r;
1232 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1233 LPCSTR szTableName)
1235 UINT r;
1236 LPWSTR table;
1238 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1239 debugstr_a(szTableName));
1241 table = strdupAtoW(szTableName);
1242 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1244 msi_free(table);
1245 return r;
1248 typedef struct _tagMERGETABLE
1250 struct list entry;
1251 struct list rows;
1252 LPWSTR name;
1253 DWORD numconflicts;
1254 LPWSTR *columns;
1255 DWORD numcolumns;
1256 LPWSTR *types;
1257 DWORD numtypes;
1258 LPWSTR *labels;
1259 DWORD numlabels;
1260 } MERGETABLE;
1262 typedef struct _tagMERGEROW
1264 struct list entry;
1265 MSIRECORD *data;
1266 } MERGEROW;
1268 typedef struct _tagMERGEDATA
1270 MSIDATABASE *db;
1271 MSIDATABASE *merge;
1272 MERGETABLE *curtable;
1273 MSIQUERY *curview;
1274 struct list *tabledata;
1275 } MERGEDATA;
1277 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1279 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1280 ((type2[0] == 'l') || (type2[0] == 's')))
1281 return TRUE;
1283 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1284 ((type2[0] == 'L') || (type2[0] == 'S')))
1285 return TRUE;
1287 return !lstrcmpW(type1, type2);
1290 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1292 MSIRECORD *dbrec, *mergerec;
1293 UINT r, i, count;
1295 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1296 if (r != ERROR_SUCCESS)
1297 return r;
1299 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1300 if (r != ERROR_SUCCESS)
1301 return r;
1303 count = MSI_RecordGetFieldCount(dbrec);
1304 for (i = 1; i <= count; i++)
1306 if (!MSI_RecordGetString(mergerec, i))
1307 break;
1309 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1310 MSI_RecordGetString(mergerec, i)))
1312 r = ERROR_DATATYPE_MISMATCH;
1313 goto done;
1317 msiobj_release(&dbrec->hdr);
1318 msiobj_release(&mergerec->hdr);
1319 dbrec = mergerec = NULL;
1321 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1322 if (r != ERROR_SUCCESS)
1323 return r;
1325 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1326 if (r != ERROR_SUCCESS)
1327 return r;
1329 count = MSI_RecordGetFieldCount(dbrec);
1330 for (i = 1; i <= count; i++)
1332 if (!MSI_RecordGetString(mergerec, i))
1333 break;
1335 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1336 MSI_RecordGetString(mergerec, i)))
1338 r = ERROR_DATATYPE_MISMATCH;
1339 break;
1343 done:
1344 msiobj_release(&dbrec->hdr);
1345 msiobj_release(&mergerec->hdr);
1347 return r;
1350 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1351 LPCWSTR table)
1353 MSIRECORD *dbrec, *mergerec = NULL;
1354 UINT r, i, count;
1356 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1357 if (r != ERROR_SUCCESS)
1358 return r;
1360 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1361 if (r != ERROR_SUCCESS)
1362 goto done;
1364 count = MSI_RecordGetFieldCount(dbrec);
1365 if (count != MSI_RecordGetFieldCount(mergerec))
1367 r = ERROR_DATATYPE_MISMATCH;
1368 goto done;
1371 for (i = 1; i <= count; i++)
1373 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1374 MSI_RecordGetString(mergerec, i)))
1376 r = ERROR_DATATYPE_MISMATCH;
1377 goto done;
1381 done:
1382 msiobj_release(&dbrec->hdr);
1383 msiobj_release(&mergerec->hdr);
1385 return r;
1388 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1390 MSIRECORD *colnames;
1391 LPWSTR str, val;
1392 UINT r, i = 0, sz = 0;
1393 int cmp;
1395 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1396 if (r != ERROR_SUCCESS)
1397 return NULL;
1401 str = msi_dup_record_field(colnames, ++i);
1402 cmp = lstrcmpW(key, str);
1403 msi_free(str);
1404 } while (cmp);
1406 msiobj_release(&colnames->hdr);
1408 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1409 if (r != ERROR_SUCCESS)
1410 return NULL;
1411 sz++;
1413 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1415 /* quote string record fields */
1416 const WCHAR szQuote[] = {'\'', 0};
1417 sz += 2;
1418 val = msi_alloc(sz*sizeof(WCHAR));
1419 if (!val)
1420 return NULL;
1422 lstrcpyW(val, szQuote);
1423 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1424 lstrcpyW(val+1+sz, szQuote);
1426 else
1428 /* do not quote integer record fields */
1429 val = msi_alloc(sz*sizeof(WCHAR));
1430 if (!val)
1431 return NULL;
1433 r = MSI_RecordGetStringW(rec, i, val, &sz);
1436 if (r != ERROR_SUCCESS)
1438 ERR("failed to get string!\n");
1439 msi_free(val);
1440 return NULL;
1443 return val;
1446 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1447 LPWSTR table, MSIRECORD *rec)
1449 LPWSTR query = NULL, clause = NULL;
1450 LPWSTR ptr = NULL, val;
1451 LPCWSTR setptr;
1452 DWORD size = 1, oldsize;
1453 LPCWSTR key;
1454 MSIRECORD *keys;
1455 UINT r, i, count;
1457 static const WCHAR keyset[] = {
1458 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1459 static const WCHAR lastkeyset[] = {
1460 '`','%','s','`',' ','=',' ','%','s',' ',0};
1461 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1462 'F','R','O','M',' ','`','%','s','`',' ',
1463 'W','H','E','R','E',' ','%','s',0};
1465 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1466 if (r != ERROR_SUCCESS)
1467 return NULL;
1469 clause = msi_alloc_zero(size * sizeof(WCHAR));
1470 if (!clause)
1471 goto done;
1473 ptr = clause;
1474 count = MSI_RecordGetFieldCount(keys);
1475 for (i = 1; i <= count; i++)
1477 key = MSI_RecordGetString(keys, i);
1478 val = get_key_value(view, key, rec);
1480 if (i == count)
1481 setptr = lastkeyset;
1482 else
1483 setptr = keyset;
1485 oldsize = size;
1486 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1487 clause = msi_realloc(clause, size * sizeof (WCHAR));
1488 if (!clause)
1490 msi_free(val);
1491 goto done;
1494 ptr = clause + oldsize - 1;
1495 sprintfW(ptr, setptr, key, val);
1496 msi_free(val);
1499 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1500 query = msi_alloc(size * sizeof(WCHAR));
1501 if (!query)
1502 goto done;
1504 sprintfW(query, fmt, table, clause);
1506 done:
1507 msi_free(clause);
1508 msiobj_release(&keys->hdr);
1509 return query;
1512 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1514 MERGEDATA *data = param;
1515 MERGETABLE *table = data->curtable;
1516 MERGEROW *mergerow;
1517 MSIQUERY *dbview = NULL;
1518 MSIRECORD *row = NULL;
1519 LPWSTR query = NULL;
1520 UINT r = ERROR_SUCCESS;
1522 if (TABLE_Exists(data->db, table->name))
1524 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1525 if (!query)
1526 return ERROR_OUTOFMEMORY;
1528 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1529 if (r != ERROR_SUCCESS)
1530 goto done;
1532 r = MSI_ViewExecute(dbview, NULL);
1533 if (r != ERROR_SUCCESS)
1534 goto done;
1536 r = MSI_ViewFetch(dbview, &row);
1537 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1539 table->numconflicts++;
1540 goto done;
1542 else if (r != ERROR_NO_MORE_ITEMS)
1543 goto done;
1545 r = ERROR_SUCCESS;
1548 mergerow = msi_alloc(sizeof(MERGEROW));
1549 if (!mergerow)
1551 r = ERROR_OUTOFMEMORY;
1552 goto done;
1555 mergerow->data = MSI_CloneRecord(rec);
1556 if (!mergerow->data)
1558 r = ERROR_OUTOFMEMORY;
1559 msi_free(mergerow);
1560 goto done;
1563 list_add_tail(&table->rows, &mergerow->entry);
1565 done:
1566 msi_free(query);
1567 msiobj_release(&row->hdr);
1568 msiobj_release(&dbview->hdr);
1569 return r;
1572 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1574 UINT r, i, count;
1575 MSIRECORD *prec = NULL;
1577 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1578 if (r != ERROR_SUCCESS)
1579 return r;
1581 count = MSI_RecordGetFieldCount(prec);
1582 *numlabels = count + 1;
1583 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1584 if (!*labels)
1586 r = ERROR_OUTOFMEMORY;
1587 goto end;
1590 (*labels)[0] = strdupW(table);
1591 for (i=1; i<=count; i++ )
1593 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1596 end:
1597 msiobj_release( &prec->hdr );
1598 return r;
1601 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1603 UINT r, i, count;
1604 MSIRECORD *prec = NULL;
1606 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1607 if (r != ERROR_SUCCESS)
1608 return r;
1610 count = MSI_RecordGetFieldCount(prec);
1611 *columns = msi_alloc(count*sizeof(LPWSTR));
1612 if (!*columns)
1614 r = ERROR_OUTOFMEMORY;
1615 goto end;
1618 for (i=1; i<=count; i++ )
1620 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1623 *numcolumns = count;
1625 end:
1626 msiobj_release( &prec->hdr );
1627 return r;
1630 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1632 UINT r, i, count;
1633 MSIRECORD *prec = NULL;
1635 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1636 if (r != ERROR_SUCCESS)
1637 return r;
1639 count = MSI_RecordGetFieldCount(prec);
1640 *types = msi_alloc(count*sizeof(LPWSTR));
1641 if (!*types)
1643 r = ERROR_OUTOFMEMORY;
1644 goto end;
1647 *numtypes = count;
1648 for (i=1; i<=count; i++ )
1650 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1653 end:
1654 msiobj_release( &prec->hdr );
1655 return r;
1658 static void merge_free_rows(MERGETABLE *table)
1660 struct list *item, *cursor;
1662 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1664 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1666 list_remove(&row->entry);
1667 msiobj_release(&row->data->hdr);
1668 msi_free(row);
1672 static void free_merge_table(MERGETABLE *table)
1674 UINT i;
1676 if (table->labels != NULL)
1678 for (i = 0; i < table->numlabels; i++)
1679 msi_free(table->labels[i]);
1681 msi_free(table->labels);
1684 if (table->columns != NULL)
1686 for (i = 0; i < table->numcolumns; i++)
1687 msi_free(table->columns[i]);
1689 msi_free(table->columns);
1692 if (table->types != NULL)
1694 for (i = 0; i < table->numtypes; i++)
1695 msi_free(table->types[i]);
1697 msi_free(table->types);
1700 msi_free(table->name);
1701 merge_free_rows(table);
1703 msi_free(table);
1706 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1708 UINT r;
1709 MERGETABLE *table;
1710 MSIQUERY *mergeview = NULL;
1712 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1713 'F','R','O','M',' ','`','%','s','`',0};
1715 table = msi_alloc_zero(sizeof(MERGETABLE));
1716 if (!table)
1718 *ptable = NULL;
1719 return ERROR_OUTOFMEMORY;
1722 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1723 if (r != ERROR_SUCCESS)
1724 goto err;
1726 r = MSI_OpenQuery(db, &mergeview, query, name);
1727 if (r != ERROR_SUCCESS)
1728 goto err;
1730 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1731 if (r != ERROR_SUCCESS)
1732 goto err;
1734 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1735 if (r != ERROR_SUCCESS)
1736 goto err;
1738 list_init(&table->rows);
1740 table->name = strdupW(name);
1741 table->numconflicts = 0;
1743 msiobj_release(&mergeview->hdr);
1744 *ptable = table;
1745 return ERROR_SUCCESS;
1747 err:
1748 msiobj_release(&mergeview->hdr);
1749 free_merge_table(table);
1750 *ptable = NULL;
1751 return r;
1754 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1756 MERGEDATA *data = param;
1757 MERGETABLE *table;
1758 MSIQUERY *dbview = NULL;
1759 MSIQUERY *mergeview = NULL;
1760 LPCWSTR name;
1761 UINT r;
1763 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1764 'F','R','O','M',' ','`','%','s','`',0};
1766 name = MSI_RecordGetString(rec, 1);
1768 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1769 if (r != ERROR_SUCCESS)
1770 goto done;
1772 if (TABLE_Exists(data->db, name))
1774 r = MSI_OpenQuery(data->db, &dbview, query, name);
1775 if (r != ERROR_SUCCESS)
1776 goto done;
1778 r = merge_verify_colnames(dbview, mergeview);
1779 if (r != ERROR_SUCCESS)
1780 goto done;
1782 r = merge_verify_primary_keys(data->db, data->merge, name);
1783 if (r != ERROR_SUCCESS)
1784 goto done;
1787 r = msi_get_merge_table(data->merge, name, &table);
1788 if (r != ERROR_SUCCESS)
1789 goto done;
1791 data->curtable = table;
1792 data->curview = mergeview;
1793 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1794 if (r != ERROR_SUCCESS)
1796 free_merge_table(table);
1797 goto done;
1800 list_add_tail(data->tabledata, &table->entry);
1802 done:
1803 msiobj_release(&dbview->hdr);
1804 msiobj_release(&mergeview->hdr);
1805 return r;
1808 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1809 struct list *tabledata)
1811 UINT r;
1812 MSIQUERY *view;
1813 MERGEDATA data;
1815 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1816 'F','R','O','M',' ','`','_','T','a','b','l','e','s','`',0};
1818 r = MSI_DatabaseOpenViewW(merge, query, &view);
1819 if (r != ERROR_SUCCESS)
1820 return r;
1822 data.db = db;
1823 data.merge = merge;
1824 data.tabledata = tabledata;
1825 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1827 msiobj_release(&view->hdr);
1828 return r;
1831 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1833 UINT r;
1834 MERGEROW *row;
1835 MSIVIEW *tv;
1837 if (!TABLE_Exists(db, table->name))
1839 r = msi_add_table_to_db(db, table->columns, table->types,
1840 table->labels, table->numlabels, table->numcolumns);
1841 if (r != ERROR_SUCCESS)
1842 return ERROR_FUNCTION_FAILED;
1845 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1847 r = TABLE_CreateView(db, table->name, &tv);
1848 if (r != ERROR_SUCCESS)
1849 return r;
1851 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1852 tv->ops->delete(tv);
1854 if (r != ERROR_SUCCESS)
1855 return r;
1858 return ERROR_SUCCESS;
1861 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1862 LPWSTR table, DWORD numconflicts)
1864 UINT r;
1865 MSIQUERY *view;
1867 static const WCHAR create[] = {
1868 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1869 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1870 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1871 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1872 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1873 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1874 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1875 static const WCHAR insert[] = {
1876 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1877 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1878 '`','N','u','m','R','o','w','M','e','r','g','e',
1879 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1880 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1882 if (!TABLE_Exists(db, error))
1884 r = MSI_OpenQuery(db, &view, create, error);
1885 if (r != ERROR_SUCCESS)
1886 return r;
1888 r = MSI_ViewExecute(view, NULL);
1889 msiobj_release(&view->hdr);
1890 if (r != ERROR_SUCCESS)
1891 return r;
1894 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1895 if (r != ERROR_SUCCESS)
1896 return r;
1898 r = MSI_ViewExecute(view, NULL);
1899 msiobj_release(&view->hdr);
1900 return r;
1903 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1904 LPCWSTR szTableName)
1906 struct list tabledata = LIST_INIT(tabledata);
1907 struct list *item, *cursor;
1908 MSIDATABASE *db, *merge;
1909 MERGETABLE *table;
1910 BOOL conflicts;
1911 UINT r;
1913 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1914 debugstr_w(szTableName));
1916 if (szTableName && !*szTableName)
1917 return ERROR_INVALID_TABLE;
1919 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1920 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1921 if (!db || !merge)
1923 r = ERROR_INVALID_HANDLE;
1924 goto done;
1927 r = gather_merge_data(db, merge, &tabledata);
1928 if (r != ERROR_SUCCESS)
1929 goto done;
1931 conflicts = FALSE;
1932 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1934 if (table->numconflicts)
1936 conflicts = TRUE;
1938 r = update_merge_errors(db, szTableName, table->name,
1939 table->numconflicts);
1940 if (r != ERROR_SUCCESS)
1941 break;
1943 else
1945 r = merge_table(db, table);
1946 if (r != ERROR_SUCCESS)
1947 break;
1951 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1953 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1954 list_remove(&table->entry);
1955 free_merge_table(table);
1958 if (conflicts)
1959 r = ERROR_FUNCTION_FAILED;
1961 done:
1962 msiobj_release(&db->hdr);
1963 msiobj_release(&merge->hdr);
1964 return r;
1967 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1969 MSIDBSTATE ret = MSIDBSTATE_READ;
1970 MSIDATABASE *db;
1972 TRACE("%d\n", handle);
1974 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1975 if( !db )
1977 IWineMsiRemoteDatabase *remote_database;
1979 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1980 if ( !remote_database )
1981 return MSIDBSTATE_ERROR;
1983 IWineMsiRemoteDatabase_Release( remote_database );
1984 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1986 return MSIDBSTATE_READ;
1989 if (db->mode != MSIDBOPEN_READONLY )
1990 ret = MSIDBSTATE_WRITE;
1991 msiobj_release( &db->hdr );
1993 return ret;
1996 typedef struct _msi_remote_database_impl {
1997 const IWineMsiRemoteDatabaseVtbl *lpVtbl;
1998 MSIHANDLE database;
1999 LONG refs;
2000 } msi_remote_database_impl;
2002 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
2004 return (msi_remote_database_impl *)iface;
2007 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
2008 REFIID riid,LPVOID *ppobj)
2010 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
2011 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
2013 IUnknown_AddRef( iface );
2014 *ppobj = iface;
2015 return S_OK;
2018 return E_NOINTERFACE;
2021 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
2023 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2025 return InterlockedIncrement( &This->refs );
2028 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
2030 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2031 ULONG r;
2033 r = InterlockedDecrement( &This->refs );
2034 if (r == 0)
2036 MsiCloseHandle( This->database );
2037 msi_free( This );
2039 return r;
2042 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
2043 LPCWSTR table, MSICONDITION *persistent )
2045 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2046 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
2047 return S_OK;
2050 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
2051 LPCWSTR table, MSIHANDLE *keys )
2053 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2054 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
2055 return HRESULT_FROM_WIN32(r);
2058 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
2059 UINT updatecount, MSIHANDLE *suminfo )
2061 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2062 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
2063 return HRESULT_FROM_WIN32(r);
2066 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
2067 LPCWSTR query, MSIHANDLE *view )
2069 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2070 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
2071 return HRESULT_FROM_WIN32(r);
2074 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
2076 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2077 This->database = handle;
2078 return S_OK;
2081 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
2083 mrd_QueryInterface,
2084 mrd_AddRef,
2085 mrd_Release,
2086 mrd_IsTablePersistent,
2087 mrd_GetPrimaryKeys,
2088 mrd_GetSummaryInformation,
2089 mrd_OpenView,
2090 mrd_SetMsiHandle,
2093 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
2095 msi_remote_database_impl *This;
2097 This = msi_alloc( sizeof *This );
2098 if (!This)
2099 return E_OUTOFMEMORY;
2101 This->lpVtbl = &msi_remote_database_vtbl;
2102 This->database = 0;
2103 This->refs = 1;
2105 *ppObj = This;
2107 return S_OK;